2016-03-28 206 views
-1

我是新的C++和我不知道如何处理这个返回类型的const引用: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[] 
.... 

很抱歉的语法错误。

回答

2

鉴于您的初始化,这是不可能的。 A const Derived&只能指代Derived类型的对象,或者来自Derived的类别的对象。

但您只创建了Base类型的对象。您没有任何类型为Derived的对象。

您可以通过书面形式尝试此:

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

这将抛出一个异常,如果有问题的指针实际上并不指向一个Derived。 (它不会,直到你有一个new Derived的地方)。

+0

我真的很感谢!我刚开始学习C++,之前没有看到“dynamic_cast <>”或“static_cast <>”。我理解在Java和C中的铸造,但还没有介绍到在C++中铸造,你有任何推荐的文章或链接引入C++铸造?谢谢! –

0

首先,如果你想返回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>>到帮助解决内存管理和异常安全问题。

+0

谢谢你的答案!我开始学习使用C++进行投射,你有推荐的链接或文章介绍这个话题吗? –

+0

也许这会帮助你:[类型转换](http://www.cplusplus.com/doc/tutorial/typecasting/) – Thomas

+0

非常感谢! –