C++ 引用

来源:互联网 发布:c语言词汇 编辑:程序博客网 时间:2024/06/16 18:58
在写C语言的时候,我们没有引用这个概念,所以当我们调用函数的时候,通常传一个指针进去调用类。但是,在传指针进去的时候,在函数内部,指针会获得传进去的对象的控制权,很可能会改变对象,去写对象。因此我们可以在指针前面加一个关键字 `const`,通过`const`去实现对对象的保护。而在C++中,有了引用,因此我们不必在函数定义的时候去传指针,更推荐使用引用。这样就避免了在参数表等地方使用`*`。下面代码将介绍如何在类中使用`const`
class A {  public:     void func1();     void func2() const{}  } const a;  int main() {     a.func1();   // C2662     a.func2();   // OK  }  

在定义类中的成员函数
void func() const{};
其实相当于

void func(const this){};

下面代码将更好的解释基类成员函数有const,而子类成员函数没有const 时,成员是如何调用函数的。

// Reference.cpp : 定义控制台应用程序的入口点。#include "stdafx.h"#include <iostream>using namespace std;class A {public:    int i;    A() {}    virtual void print()const;        //实际上,这里的const其实就是指this指针const,即 virtual void print(const this)    ~A() {}};void A::print()const    //等价于print(const this){    cout << "A::print()" << endl;}class B :public A {public:    int j;    B() {}    void print();   /*  这里实现函数隐藏基类(其实是子类再定义一个函数,实现对基类的隐藏),详情见:    http://blog.csdn.net/qq_30366449/article/details/76038802    */    void func(const A& t)    {        t.print();    }    ~B() {}};void B::print(){    cout << "B::print()" << endl;}int main(){    B b;    const A m;    b.func(m);    b.print();    A* p = &b;    p->print();    return 0;}