我有一个基类(Base
),其构造函数的参考作为参数。在我的派生类的构造函数中,我调用超类的构造函数,当然我需要传递一个引用作为参数。但我必须获得其中的返回类型是值的方法这样的说法......C++:引用作为构造函数参数,帮助
我会给出一个简单的例子:
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.
}
};
我怎样才能解决这个问题?
基础构造函数是否修改对象,对其进行引用?有什么限制?我的意思是,代码中的哪些部分可以修改,哪些部分必须保持不变? – 2010-07-07 16:05:07
使参数成为常量引用。 – 2010-07-07 16:06:24
const引用如何提供帮助?它仍然是一个不再存在的东西的参考。 – 2010-07-07 16:31:36