const这个关键字大家肯定都很熟悉,它的意思就是,被我修饰(保护)的东西,你不能改,下面来研究一下它!
1. 常量
int main(){ const int value = 1; value = 2; return 0; }
上面的代码是会报错的,被const修饰的value是无法修改的。
2. 常成员函数
class Test{ public: void test() const{ i = 1; j = 2; } private: int i; int j; };
上面的代码是会报错的,常成员函数是不能修改类的成员变量的。
3. 常对象和常成员函数
#include <iostream> using namespace std; class Test{ public: void test() const{ cout<<"const function"<<endl; } void test1(){ cout<<"test1 function"<<endl; } private: int i; int j; }; int main(){ const Test t; t.test(); t.test1(); return 0; }
上面的代码是会报错的,t.test1();这段代码报的错,因为test1()不是个常成员函数,所以会报错!-------常对象只能调用其常成员函数。
4. 常量形参
#include <iostream> using namespace std; int testFunc(const int& value){ value = 12; return value; } int main(){ int value = 1; testFunc(value); return 0; }
上面的代码是会报错的,因为testFunc()的形参是const的,无法修改。
5. 其他常
class Test{ public: const void test(){ cout<<"const function"<<endl; } private: int i; int j; };
上面的代码在test()前加了const,实际上这样是毫无效果的,即使void是int也没有用,这种定义就是闲的蛋疼。
#include <iostream> using namespace std; class Test{ public: Test(){ instance = new Test(); } const Test& test(){ cout<<"const function"<<endl; return *instance; } private: Test *instance; }; int main(){ return 0; }
上面的代码就有意义了,返回的instance不能被修改。