C++从函数返回对象时使用自定义复制构造函数

C++ using custom copy constructor when object returned from a function?

本文关键字:自定义 复制 构造函数 函数 返回 对象 C++      更新时间:2023-10-16
class Tree
{
 private:
double height;
string name;
public:
Tree()
{
    cout << "Default constructor of class Tree." << endl;
    height = 0;
    name = "";
}
Tree(double he, string na)
{
    cout << "Parameterized constructor of class Tree." << endl;
    height = he;
    name = na;
}
Tree(Tree &t)
{
    cout << "Customized copy constructor of class Tree." << endl;
    height = t.height;
    name = t.name;
}
void toString()
{
    cout << name << " " << height << endl;
}
};
Tree getTree()
{
Tree t(321, "abc");
return t;
}
int main(int argc, char* argv[])
{
Tree t1(123, "xyz");
Tree t2 = getTree();
t2.toString();
return 0;
}

从函数 getTree(( 返回的树对象应该使用自定义的复制构造函数复制到对象 t2,而编译器抱怨"错误:没有匹配函数调用'树::树(树('"。

复制构造函数需要接受对象的 const 版本。将复制构造函数更改为:

Tree(const Tree &t)
{
    cout << "Customized copy constructor of class Tree." << endl;
    height = t.height;
    name = t.name;
}

这将清除错误。

t2 = getTree()调用复制

构造函数Tree(Tree &t),它接受对类树实例的引用,而函数Tree getTree()返回对象,而不是引用。该问题的解决方案是让函数 Tree getTree() 返回引用:Tree& getTree()

仅供您参考,复制构造函数应该接受一个const Tree &,这也解决了问题。编写这样的复制构造函数是一种规范:

Tree(const Tree &t) {
    // Do something here
}

编辑:您可能会收到一条警告,指出返回对局部变量的引用,但您可以选择忽略该警告,也可以更改复制构造函数。就个人而言,我会更改复制构造函数。

Tree getTree()
{
  Tree t(321, "abc");
  return t;
}

getTree((,这里按值返回一个本地对象。因此,创建了一个临时对象(临时对象是const(,这意味着Copy-Ctor正在传递一个常量对象,而根据定义,它期望非常量对象。将 Copy-Ctor 参数更改为 const 将解决此问题。