【发布时间】:2010-07-07 16:00:44
【问题描述】:
我有一个基类(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.
}
};
我该如何解决这个问题?
【问题讨论】:
-
Base 构造函数是否修改对象,它获得的引用?有什么限制?我的意思是,您可以修改代码的哪些部分,哪些部分必须保持不变?
-
使参数成为常量引用。
-
const 参考有什么帮助?它仍然是对不再存在的事物的引用。
-
@Michael 不,不是。如果使用 const 引用,则可以将该引用绑定到临时引用,例如返回值。他不能做的是将该引用存储在正在构造的对象中,但我不清楚他正在做什么。
-
@Neil - 我认为只要构造函数运行,const 引用就会存在,但我们不知道基本构造函数是否保存了一些引用以供以后使用。
标签: c++ constructor reference argument-passing