从方法中按值返回类类型的变量

Returning an variable of class' type by value from the method

本文关键字:类型 变量 返回 方法      更新时间:2023-10-16

先生们,美好的一天!让我们考虑一下代码:

class Test
{
    int a;
public:
Test(){}
Test( Test& t){cout<<"hellon";} //copy constructor
Test foo() { return Test();}


};
int main()
{
    Test t;

}

问题是给定的代码没有编译。如果我们删除复制构造函数,一切顺利。问题出在哪里?添加常量 - Test(const Test& t)解决了问题,但我不明白为什么。谁能解释一下?谢谢!

Test( Test& t){cout<<"hellon";}

是的,这是一个复制构造函数。

但是,我们通常这样写:

Test(const Test& t){cout<<"hellon";}

那是因为它以这种方式更有用;这是我们从"临时"(例如你的表达式Test())复制构造Test的唯一方法,因为只有引用到const(和右值引用)可以绑定到临时引用。

这与以下问题相同:

      int& r1 = 3;    // :(
const int& r2 = 3;    // :D

或:

      int& r1 = f();  // :(
const int& r2 = f();  // :D