class test {
public:
test &operator=(const test & other){} // 1
const test & operator+(const test& other) const {} // 2
const test & operator+(int m) {} //3
private:
int n;
};
int main()
{
test t1 , t2, t3;
// this works fine t1 = t2.operator+(t3) , calls 2 and 1
t1 = t2 + t3;
// this works fine t1 = t2.operator+ (100). calls 3 and 1
t1 = t2 + 100;
//this works fine t1 = (t2.operator+ (100)).operator+ (t3)
t1 = t2 + 100 +t3;
//why is the error in this one ????
// it should be t1 = (t2.operator+ (t3)).operator+ (100)
t1 = t2 + t3 + 100;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
因为t2 + t3返回的对象是const,所以你不能调用它的非const函数(3).
它在"t1 = t2 + 100 + t3;"的情况下工作正常,因为t2 + 100返回的对象也是const,但是你正在调用它的const函数(2),这没关系.
| 归档时间: |
|
| 查看次数: |
374 次 |
| 最近记录: |