C++ 返回对对象的常量引用
我在下面的代码中有冲突C++ 返回对对象的常量引用,c++,reference,operator-overloading,constants,C++,Reference,Operator Overloading,Constants,我在下面的代码中有冲突 #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 constr
#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;
}
为了让它工作,我应该让操作符=
像:
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
TestApp&operator=(常量TestApp&obj){
cout提供赋值运算符的正确方法是如下声明:
TestApp &operator=(const TestApp &obj) {
cout << "= operator\n";
return *this;
}
提供赋值运算符的正确方法是如下声明:
TestApp &operator=(const TestApp &obj) {
cout << "= operator\n";
return *this;
}
您可能不赋值常量对象。例如,考虑这个简单的代码< /P>
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){
CUT不能分配常量对象。例如,考虑这个简单的代码< /P>
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和解决方案1对第2行不起作用?是的,我知道,所以我用注释来说明代码对哪一行起作用。那么问题是什么?请阅读一篇好的介绍。const
适用于变量,并且是对编译器的承诺。请参阅例如And和解决方案1对第2行不起作用?是的,我知道,所以我用注释来说明哪一行代码可以工作。那么问题是什么呢?请阅读一篇好的介绍。const
适用于变量,并且是对编译器的承诺。请参阅例如和