![](/img/trans.png)
[英]Vector of base class pointers to access member functions from derived classes? The correct way?
[英]Dynamic binding and virtual functions - Vector of base class objects, access the "correct" member function
我对 C++ 还很陌生,我试图尽可能多地了解该语言和底层机制。
我对一个特定情况感到困惑,当我有两个类(Base 和 Derived)时,我似乎无法访问正确的成员函数,即使我将它们定义为虚拟。
class Base {
public:
virtual void print() { std::cout << "Base" << std::endl; };
};
class Derived : public Base {
public:
virtual void print() { std::cout << "Derived" << std::endl; };
};
int main() {
Base b;
Derived d;
b.print();
d.print();
Base* p1 = &b;
Base* p2 = &d;
p1->print();
p2->print();
std::vector<Base> v { b, d };
v[0].print();
v[1].print(); // Why doesn't this print "Derived?"
return 0;
}
输出:
Base
Derived
Base
Derived
Base
Base <- ??
virtual
似乎与Base
类型的指针“工作”,但不适用于vector<Base>
对象。
这是怎么回事?
因为对象切片。 创建矢量时,您将对象复制到其中。
std::vector<Base> v{ b, d };
问题是在std::vector
您只有Base
类型的对象, NOT Base
和Derived
。 如果您希望 C++ 中的容器具有多态行为,通常使用点来实现,因为您无法在其中保留原始引用。
std::vector<Base*> v{ &b, &d };
for (Base* ptr : v) {
ptr->print();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.