c++返回一个对象的const引用
c++ returning a const reference of an object
我是c++的新手,我不知道如何处理这种返回类型:
CCD_ 1。
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'
如何返回对象的常量引用?我很困惑。
我通过以下代码初始化了构造函数中的变量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
的对象或从const Derived& myClass::getDerived(){} const
0派生的类的对象。
但是您只创建了Base
类型的对象。您没有任何类型为Derived
的对象。
您可以通过以下方式尝试:
virtual const Derived& getDerived() const
{
return dynamic_cast<Derived const &>(*b[indexOfDerived]);
}
如果所讨论的指针实际上没有指向CCD_ 13。(它不会,除非你在某个地方有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>>
来帮助解决内存管理和异常安全问题。
相关文章:
- 将const引用参数初始化为默认参数会导致悬空引用吗
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 将对象传递给函数而不将其包装到 std::ref 中,而参数被指定为 const 引用
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 对临时对象的Const引用不会延长其生存期
- 对 const 引用参数使用默认值会导致崩溃
- 在运算符重载中使用带有 const 引用的 friend 函数
- C++通过 const 引用传递时不调用派生类函数
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么要返回对小类成员的 const 引用?
- C - 最好将枚举类作为值或const引用
- RVO:返回由值传递的值,即使显式分配给 const 引用也是如此
- const引用与可变成员的对象
- 每当传递lvalue时,每当通过rvalue传递时,将const引用存储
- 对类成员而不是 getter 的 Const 引用
- 从类型 'Matrix&' 的右值初始化 类型的非 const 引用无效 'Matrix'
- 在函数中使用 const 引用参数访问函数中成员的最佳实践 C++.
- STD ::配对的const引用如何工作
- 为什么我的C 函数拒绝返回const引用