3.C++函数声明后加const

#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();//错误,const的对象不能对非const函数进行访问.
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的成员函数。


猜你喜欢

转载自blog.csdn.net/u011124985/article/details/80089913