const

来源:互联网 发布:天猫魔盒上的直播软件 编辑:程序博客网 时间:2024/05/29 03:28

const成员函数必须在声明和定义时都注明const

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify
the object for which it is called.
To declare a constant member function, place the const keyword after the closing parenthesis of the argument list.
The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members
or call any member functions that aren't constant.

 const member variable can only be initialized in constructor initialization list.

下例用来说明:

1)const成员函数不能修改成员变量

2)非const成员函数可以访问const和非const成员变量,但不能修改const成员变量

class Base_const{public:void fun() const;void nonconst_fun_access_const_var();Base_const(int x):i(1),c(x) {}private:int i;const int c;};void Base_const::fun() const{//i=4; //const成员函数不能修改成员变量cout << "i= "<<i <<endl<<"c=" << c <<endl;nonconst_fun();//error: non_const function can't be called by const function};//非const成员函数可以访问const和非const成员变量,但不能修改const成员变量void Base_const::nonconst_fun(){c++; //error:不能修改const成员变量i++;cout << c <<endl;cout << i <<endl;}#endif /* MYCONST_H_ */


原创粉丝点击