对函数返回类型进行const后返回的别名无法调用对象函数有关问题?
【求助】对函数返回类型进行const后返回的别名无法调用对象函数问题???先看代码:#includeiostreamusing na
【求助】对函数返回类型进行const后返回的别名无法调用对象函数问题???
先看代码:
#include<iostream>
using namespace std;
class WS{
public:
void set(int x){
i=x;
}
int get(){return i;}
private:
int i;
};
const WS& func(WS &one){
return one;
}
void main(){
WS Lee;
Lee.set(123);
const WS& Kee=func(Lee);
cout<<Kee.get()<<endl;//为什么这句话会报错??????
}
为什么在使用函数返回的别名调用对象的函数时会提示:无法将const WS 转换为 WS& ??
我并没有使用函数对返回的别名对象进行修改,仅仅是调用函数进行输出!!!
[解决办法]const引用不能调用该对象的非const成员函数
[解决办法]const WS& Kee=func(Lee)
这句话拿到的是一个const引用,所以只能使用该对象的const function
get虽然没有做任何修改,但仍然声明成了非常量函数
这个错误是静态类型检测错误。
你可以在WS中定义
int get() { return i;}
int get() const {return i;}
这样Kee.get()就会调用get() const方法