无法使用函数的返回值初始化对象。为什么?

Cannot initialize object with returning value of a function.. Why?

我写这段简单的代码是为了理解 c++ 中复制构造函数的功能。当我直接用“obj1”初始化“obj2”时,它工作正常。但是当我尝试使用函数“func()”的返回对象初始化“obj2”时,它显示错误:

error: cannot bind non-const lvalue reference of type 'MyInt&' to an rvalue of type '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) {
    this->x = obj.x;
    cout<< "copy constructor called" << endl;
}

参数MyInt& obj是引用,不是const

这表示您希望能够从中读取并向其写入

C++ 不允许将 临时(也称为“右值”)作为此参数传递,从而避免某些错误。因为写入临时文件几乎肯定是错误的。不管你写什么都会丢失。

但是,您的函数不会写入该参数。您可以通过 const.

来表明您不打算写入引用
MyInt(const MyInt& obj) {
    this->x = obj.x;
    cout<< "copy constructor called" << endl;
}

此更改将允许将临时对象传递给此构造函数。