调用const对象的函数时应将函数定义为 * *()const{}

例如:

#include<iostream.h>
class complex
{
public:
 complex(double a,double b):real(a),imag(b)
 {}
 complex(){}
 friend complex operator +(const complex& a,const complex& b);
 double getreal(){return real;}              //错误,const a不能调用非const函数
 double getimag(){return imag;}    //错误,const a不能调用非const函数
 void print();
private:
 double real,imag;
};
complex operator +(const complex& a,const complex& b)
{
 complex c;
 c.real=a.getreal()+b.getreal();
 c.imag=a.getimag()+b.getimag();
 return c;
}
void complex::print()
{
 cout<<"("<<real<<","<<imag<<")"<<endl;
}
int main()

 double a,b;
 cout<<"请输入第一个数的实部和虚部:"<<endl;                  //new出来
 cin>>a>>b;
 complex *p1=new complex(a,b);
 cout<<"请输入第二个数的实部和虚部:"<<endl;                 
 cin>>a>>b;
 complex *p2=new complex(a,b);
 complex c3;
 c3=*p1+*p2;
 c3.print();
 delete p1;
 delete p2;
 return 0;
}

 

 

 应将

 double getreal(){return real;}             改成 double getreal()const{return real;}   

 double getimag(){return imag;}    改成 double getimag()const{return imag;}  

posted on 2017-06-02 15:08  么训  阅读(628)  评论(0编辑  收藏  举报