gpt4 book ai didi

C++:引用作为构造函数参数,帮助

转载 作者:行者123 更新时间:2023-11-27 23:33:14 25 4
gpt4 key购买 nike

我有一个基类 (Base),其构造函数将引用作为参数。在我的派生类的构造函数中,我调用父类(super class)构造函数,当然我需要传递一个引用作为参数。但是我必须从返回类型为值的方法中获取该参数...

我举一个简短的例子:

class Base
{
public:
Base(MyType &obj) { /* do something with the obj */}
};

class Derived : public Base
{
public:
Derived(MyOtherType *otherType) :
Base(otherType->getMyTypeObj()) // <--- Here is the error because (see *)
{
// *
// getMyTypeObj() returns a value and
// the Base constructor wants a reference...
}
};

class MyOtherType
{
public:
MyType getMyTypeObj()
{
MyType obj;
obj.setData( /* blah, blah, blah... Some data */);
return obj; // Return by value to avoid the returned reference goes out of scope.
}
};

我该如何解决这个问题?

最佳答案

将基类更改为:类基础
{
民众:
Base(const MyType &obj) {/* 对 obj 做一些事情 */}
};

更新:如果你想修改 obj 你显然不能有一个 const 引用。在这种情况下,您可以:

1)按值传递参数。这将产生拷贝的开销,但避免以后必须显式释放它。

2) 将 MyOtherType::getMyTypeObj() 更改为

MyType& MyOtherType::getMyTypeObj()
{
MyType* obj = new MyType();
obj->setData( /* blah, blah, blah... Some data */);
return *obj;

在这种情况下,记得在用完对象后将其删除。

关于C++:引用作为构造函数参数,帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3196585/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com