【发布时间】:2021-09-10 20:38:50
【问题描述】:
我编写了这个简单的代码来理解 C++ 中复制构造函数的功能。当我直接用“obj1”初始化“obj2”时,它工作正常。但是当我尝试使用函数“func()”的返回对象初始化“obj2”时,它显示错误:
错误:无法将“MyInt&”类型的非常量左值引用绑定到“MyInt”类型的右值
为什么会这样?
代码:
#include<bits/stdc++.h>
using namespace std;
class MyInt
{
int x;
public:
MyInt()
{
cout<< "default constructor called" << endl;
}
MyInt(int x)
{
cout<< "constructor with initializer called" << endl;
this->x = x;
}
MyInt(MyInt& obj) {
this->x = obj.x;
cout<< "copy constructor called" << endl;
}
~MyInt()
{
cout<< "destructor called" << endl;
}
};
MyInt func(MyInt obj)
{
return obj;
}
int main()
{
MyInt ob1(2);
//MyInt ob2 = ob1; //works perfectly fine: "copy constructor called"
MyInt ob2 = func(ob1); //giving error
}
【问题讨论】:
-
请注意,您的复制构造函数的格式为
MyInt(MyInt& obj)而不是MyInt(const MyInt& obj)。在 C++ 中,您 cannot 将纯右值(如func()的返回值)绑定到非 const 左值引用。 -
我想我错过了这个,因为强制复制省略。
-
不相关:必须链接到Why should I not #include <bits/stdc++.h>? 但是如果你仍然使用它并将它与 using namespace std; 结合起来,things can get really weird。
-
也许您可以解释一下您做什么和不了解错误消息?对“为什么”有任何回答?可能会尝试猜测如何改写该消息。你知道什么是右值吗?你知道它不能绑定到诸如
MyInt&这样的非常量引用吗?
标签: c++ initialization copy-constructor