3. Add const after C++ function declaration

#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的成员函数。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857665&siteId=291194637