我在下面的代碼中有衝突。返回一個對象的const引用
#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行工作? – deviantfan
是的,我知道,所以我把評論,以顯示代碼將工作的哪一行。 –
那麼問題是什麼? – juanchopanza