const函数的想法是不允许修改他们调用的对象。如果可能,让尽量多的函数称为const函数,来避免对象的以外修改。 123456789101112131415161718 #include<iostream>using namespace std; class Test { int value;public: Test(int v = 0) {value = v;} // in this function. int () const {return value;} }; int main() { Test t(20); cout<<t.getValue(); return 0;} Output: 1 20 当一个函数被声明为const,它可以被任何类型的对象调用。非const函数只能被非cosnt对象调用。 123456789101112131415 #include<iostream>using namespace std; class Test { int value;public: Test(int v = 0) {value = v;} int () {return value;}}; int main() { const Test t; cout << t.getValue(); return 0;} Output: 12 passing 'const Test' as 'this' argument of 'int Test::getValue()' discards qualifiers 赞微海报分享
近期评论