我有一个基类(Base
),它的构造函数将引用作为参数。在我的派生类它的构造函数中,我调用超类构造函数,当然我需要传递一个引用作为参数。但是我必须从返回类型为按值的方法中获取该参数...
我将举一个简短的例子:
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.
}
};
我怎么解决这个问题?