簡體   English   中英

C ++返回對象的const引用

[英]c++ returning a const reference of an object

我是C ++的新手,我不確定如何處理此返回類型:

const Derived& myClass::getDerived(){} const

myClass具有成員變量Base**b

#include "Base.h"
Class myClass
{
    public:
         virtual const Derived& getDerived() const;
    .....
    protected:
         Base**b;
}

派生類繼承自基類:

Class Derived : public Base
{
    ....
}

我試過了: return b[indexOfDerived]; 並且錯誤是: reference to type 'const Derived' could not bind to an lvalue of type 'Base *'

我也嘗試過: return *this->b[indexOfDerived]; 錯誤是: no viable conversion from returned value of type 'Part' to function return type 'const CPU'

如何返回對象的const引用? 我很混亂。

我通過以下代碼在構造函數中初始化了變量Base**b

myClass::myClass()
{
     b = new Base*[size];
     for(int i = 0; i < size; i++)
     {
          b[i] = new Base();
     }
}
....
// deallocating memory in destructor by using delete and delete[]
....

對不起,語法錯誤。

根據您的初始化,這是不可能的。 const Derived&只能引用Derived類型的對象或從Derived的類的對象。

但是,您僅創建了Base類型的對象。 您沒有任何Derived類型的對象。

您可以通過編寫以下內容來嘗試:

virtual const Derived& getDerived() const
{
    return dynamic_cast<Derived const &>(*b[indexOfDerived]);
}

如果所討論的指針實際上未指向Derived ,則將引發異常。 (這不會,除非您在某個地方有一個new Derived )。

首先,如果要返回Derived ,則應創建Derived

b[i] = new Base(); 

您必須進行強制轉換才能將Base*轉換為Derived*

const Derived& getDerived() const
{
    return *static_cast<Derived const*>( b[0] );
} 

考慮使用vector<Base*>或更好的vector<unique_ptr<Base>>來幫助解決內存管理和異常安全問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM