C++从函数返回对象时使用自定义复制构造函数
C++ using custom copy constructor when object returned from a function?
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 将解决此问题。
相关文章:
- 将文件复制到自定义位置,存在字符串转换问题
- C++11:没有复制构造函数的自定义基于范围的循环
- 用于 XML 的自定义 wxDataObject 格式,用于复制粘贴支持
- 自定义类对象的C++向量 - 复制构造函数已删除 - std::ifstream
- 复制构造函数C++中自定义类的动态数组
- 自定义类中的移动与复制性能
- 如何在自定义删除器的情况下复制unique_ptr
- 如何将sf::Font复制到自定义池分配的内存中
- 自定义复制动态数组
- 如何将变量从主机上的自定义类数组复制到 CUDA 中设备上的浮点数组中
- 如何在C++中使用默认和自定义复制构造函数
- `不可复制`与自定义析构函数
- 将剪切、复制、粘贴快捷方式更改为Qt 5中的自定义槽
- 为什么要求自定义分配器是可复制的
- 从c++到OpenGL的数据复制使用自定义容器,但不使用std::tuple
- QT c++可以使用自定义mime类型在多个应用程序上复制和粘贴
- 自定义类的Static_cast会导致复制赋值失败
- 关于C++中的分段错误的问题很可能是由自定义复制构造函数引起的
- C++从函数返回对象时使用自定义复制构造函数
- 自定义复制赋值操作符使程序崩溃(c++)