返回返回基本或派生clss指针的函数的返回值

时间:2017-12-12 20:53:20

标签: c++ polymorphism

考虑下面代码中显示的类的关系:

android:adjustViewBounds

为什么打印ImageView而不是class Base { virtual getValue() { return 0; } }; class Derived: public Base { getValue() override { return 1; } }; class Another { Base* makeClass( bool ); void createVector(); }; Base* Another::makeClass( bool base ) { if( base ) { return new Base(); } else { return new Derived(); } } void Another::createVector() { std::vector<Base> vector; vector.emplace( *makeClass( false ) ); std::cout << vector[0].getValue(); } ? 是否在添加到向量时将0转换为1

1 个答案:

答案 0 :(得分:0)

“添加到向量时,它是否将Derived*转换为Base?”是。

vector.emplace( *makeClass( false ) );

*makeClass( false )取消引用返回的指针并将其切成Base。此Base存储在vector

推荐阅读:What is object slicing?

要解决此问题,

 std::vector<Base *> vector; // but watch out for Cylons
 vector.emplace( makeClass( false ) );
 std::cout << vector[0]->getValue();

或者更好的是,研究std::unique_ptr并让智能指针内存管理为您工作。