class Test
{
public:
Test();
~Test();
int num;
int fun();
int fun(int b) const;
int fun(int b);
};
Test::Test()
{
cout << "Test()" << endl;
}
Test::~Test()
{
}
int Test::fun()
{
cout << " int fun();" << endl;
return 0;
}
int Test::fun(int b)
{
cout << " int fun(int b);" << endl;
num = 2;
return 0;
}
int Test::fun(int b) const
{
cout << " int fun(int b) const;" << endl;
return 0;
}
int main()
{
Test test;
const Test testC;
test.fun();
test.fun(3);
testC.fun(3);
system("pause");
return 0;
}
代码的输出为:
Test()
Test()
int fun();
int fun(int b);
int fun(int b) const;
const修饰的函数不仅能限制函数去修改成员变量,同时也能实现函数的重载。要想调用const修饰的重载函数,需要用const对象去调用。
另外要注意的是,如果一个函数用const修饰了,但是这个函数没有实现重载,那么非const对象和const对象都能调用这个函数。
特别注意的是,const修饰的对象只能调用const修饰的函数,比如,testC.fun()是错误的,因为fun()是非const的,而testC是const的。
原文:https://blog.youkuaiyun.com/a512745183/article/details/52590223