我是新的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[]
....
很抱歉的语法错误。
我真的很感谢!我刚开始学习C++,之前没有看到“dynamic_cast <>”或“static_cast <>”。我理解在Java和C中的铸造,但还没有介绍到在C++中铸造,你有任何推荐的文章或链接引入C++铸造?谢谢! –