我有一個基類(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