#include<iostream>
using namespace std;
class F
{
int n;
int d;
public:
F(int n=0, int d=1):n(n),d(d){};
friend istream& operator>>(istream& in,F& a);
int getn(){return n;}
int getd(){return d;}
};
istream& operator>>(istream& in,F& a)
{
char c;
in>>a.n>>c>>a.d;
return in;
}
ostream& operator<<(ostream& out,const F& a)
{
out<<a.getn()<<'/'<<a.getd();
return out;
}
int main()
{
F a,b;
cout<<"输入两个分数"<<endl;
cin>>a>>b;
cout<<a<<b;
getchar();
}
上述代码报错:error C2662: “F::getn”: 不能将“this”指针从“const F”转换为“F &”1> 转换丢失限定符
由于const对象在调用成员函数的时候,会将this指针强行转换为const this,所以它将无法找到相应的const getn()和getd()函数,并且编译器也无法将一个const的对象转化为一个普通对象来调用这个普通的getn()和getd()方法,所以就会产生如题的编译错误
解决方法:
int getn()const{return n;}
int getd()const{return d;}
参数是const修饰的函数其内部调用的类成员函数也必须是const