#include
<iostream>
using
namespace
std
;
class
complex
{
public:
complex();
void
display
()
const
;
void
test
();
private:
double
real;
double
imag;
};
int
main
()
{
complex c;
c.
display
();
const complex cc;
cc.test();//Error, const objects cannot access non-const functions.
return
0
;
}
complex::complex
()
{
real =
0.0
;
imag =
0.0
;
}
void
complex::display
()
const
{
real = 5.5;//错误,
函数后加了const的,不可以对成员变量进行赋值.
cout<<real<<
" "<<imag<<endl;
}
在类成员函数的声明和定义中,
const的函数不能对其数据成员进行修改操作。
const的对象,不能引用非const的成员函数。