【发布时间】:2014-03-29 09:50:22
【问题描述】:
我在下面的代码中有冲突。
#include <iostream>
using std::cout;
using std::endl;
class TestApp {
public:
TestApp(int _x = 9) {
cout << "default constructor\n";
}
TestApp(const TestApp &app) {
cout << "Copy constructor\n";
}
~TestApp() {
cout << "destructor\n";
}
void setX(int _x) {
}
const TestApp &operator=(TestApp &obj) {
cout << "= operator\n";
return *this;
}
void setX(int _x) {
cout << "Inside setX\n";
}
};
int main() {
TestApp app1;
TestApp app2;
TestApp app3;
(app1 = app2) = app3; // 1
app1 = app2 = app3; // 2
app1.setX(3)
return 0;
}
我收到此错误:对于第 1 行 main.cpp:38: error: passing ‘const TestApp’ as ‘this’ argument of ‘const TestApp& TestApp::operator=(TestApp&)’ discards qualifiers
但是我可以使用app1.setX(3);
main.cpp:38: error: no match for ‘operator=’ in ‘app1 = app2.TestApp::operator=(((TestApp&)(& app3)))’
main.cpp:28: note: candidates are: const TestApp& TestApp::operator=(TestApp&)
为了使其正常工作,我应该将operator= 设为:
TestApp &operator=(const TestApp &obj) {
cout << "= operator\n";
return *this;
} // works for 1
TestApp &operator=(TestApp &obj) {
cout << "= operator\n";
return *this;
} // works for 2
为什么如果我删除 const 关键字它会起作用?并且在第 1 行之后 app1 对象不是常量。
【问题讨论】:
-
解决方案 1 不适用于第 2 行?
-
是的,我知道,所以我添加注释以显示代码适用于哪一行。
-
那么问题是什么?
-
请阅读一个很好的介绍。
const适用于变量,是对编译器的承诺。参见例如 stackoverflow.com/questions/4059932/… 和 stackoverflow.com/questions/2139224/…
标签: c++ reference operator-overloading constants