我在下面的代码中有冲突。
#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
对象不是恒定的。
您不能分配常量对象。例如考虑这个简单的代码
const int x = 10;
x = 20;
编译器将对第二条语句发出错误,因为x是一个常量对象,可能未分配。
声明同样有效
(app1 = app2) = app3;
此处的表达式(app1 = app2)
返回可能未分配的常量引用,
常量引用并不意味着它引用的对象本身是常量。考虑下面的例子
int x = 10;
const int &rx = x;
x = 20;
rx = 30;
尽管rx被定义为常量引用,但是您可以更改对象x本身。您可能不使用该引用来分配对象x,因此编译器将对最后一条语句发出错误。
我们经常在函数的参数声明中使用常量引用,以防止更改它们在函数内部引用的对象。例如
void f( const int &x )
{
x = 20; // compilation error
}
int x = 10;
f( x );
因此,定义对非常量对象的常量引用不会使对象本身成为常量。它仅防止使用此引用更改对象。
而且您只需要定义一个副本分配运算符
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 TestApp &obj
当然,您可能会将这两个运算符放在一起,但没有第二个运算符的意义。
另一方面,您可能不会只有第二个运算符。在这种情况下,您将无法使用将它们分配给其他对象的常量对象。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句