【发布时间】:2016-10-07 13:26:44
【问题描述】:
谁能告诉我为什么下面的代码:
#include <iostream>
using namespace std;
class Test {
int a, b, c;
public:
Test() : a(1), b(2), c(3) {}
const void print() {cout << a << b << c;}
int sum() {return (a+b+c);}
};
const Test& f(const Test& test) {
test.print();
// cout << test.sum();
return test;
}
main() {
Test x;
cout << "2: ";
y = f(x);
cout << endl;
}
给出编译错误
“错误:将 'const Test' 作为 'this' 参数传递会丢弃限定符”
?
我的print() 方法是const,这是我所理解的所有必要条件。对我来说,f() 中的(已注释掉的)sum() 方法应该会出错,但 print() 方法不会。如果有人能指出我误解的地方 - 那太好了。
【问题讨论】:
标签: c++