来源:互联网 发布:ubuntu还原初始状态 编辑:程序博客网 时间:2024/04/27 04:31

对于基本数据类型,函数的参数前面加不加const都是一样的,但对于指针和引用,参数前面加const与不加const是不同类型的参数,因此是重载函数。 

 

如下代码编译器认为是重复定义

int comp(int a)

{

return a;

}

int comp(const int a)

{

return a;

}

 

以下代码编译器会顺利编译通过

int comp(int *a)

{

return *a;

}

int comp(const int *a)

{

return *a;

}int comp(int &a)

{

return a;

}

int comp(const int &a)

{

return a;

}

 

对于类的成员函数 如:

class VAC

{

public:

    int f() const

    {

        return 3;

    }

 

    int f() 

    {

        return 5;

    }     

};

上述编译能够成功的原因是

其实就是对类成员函数有一个隐藏的this指针这个事实不清楚才有这种疑惑的,假如我们不隐藏this,函数写出这样,你还有疑惑么? 

 

C/C++ code

 

class VAC

{

public:

    int f(const VAC * this) 

    {

        return 3;

    }

 

    int f(VAS * this) 

    {

        return 5;

    }      

};

 

 

 

如果C++不把this隐藏起来,你看上面是不是就是一个重载?所以,永远记得那个this