📄 constmember.cpp
字号:
//: C08:ConstMember.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
class X {
int i;
public:
X(int ii); //one parameter constructor
int f() const; //const memeber function,(1) it enforces constness during the function definition by issuing an error message if you try to change any members of the object or call a non-const member function. (2)tell the compiler the function can be called for a const object.
int f1();
};
X::X(int ii) : i(ii)
{}
//Note that the const keyword must be repeated in the definition or the compiler sees it as a different function.
//Since f( ) is a const member function, if it attempts to change i in any way or to call another member function that is not const, the compiler flags it as an error.
int X::f() const
{
return i;
}
int X::f1()
{
return i;
}
void main()
{
X x1(10);
const X x2(20); //const object
x1.f();
x1.f1(); //You can see that a const member function is safe to call with both const and non-const objects. Thus, you could think of it as the most general form of a member function (and because of this, it is unfortunate that member functions do not automatically default to const). Any function that doesn’t modify member data should be declared as const, so it can be used with const objects.
x2.f(); // x2.f1(); //only a const member function may be called for a const object.
} ///:~
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -