向量中的多态性

时间:2016-12-20 10:57:26

标签: c++ pointers vector polymorphism

#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;

class base {
    int data;
public:
    base(int d = 100) : data(d) {}
    virtual int getData() const {return data;}
};

class derived : public base {
    int dData;
public:
    derived(int dd = 32) : base(), dData(dd) {}
    virtual ~derived(){}
    int getData() const {return dData;}
};



int main(){
    std::vector<base> vec;
    base A(20);
    derived B(32);

    vec.push_back(A);
    vec.push_back(B);

    for(unsigned int i=0; i < vec.size(); i++)
        cout << "vector[" << i << "] :" << vec[i].getData() << endl;

    base * ptr;
    ptr = &A;
    cout << "Base pointing: " << ptr->getData() << endl;

    ptr = &B;
    cout << "Derived pointing: " << ptr->getData() << endl;

}

在代码上方,我创建了一个向量类型的向量,并将派生对象放入其中。当我试图读取值时,我无法得到正确的值。即使我在我的类中具有相同名称的函数之前放置'virtual'语句。但在指针方式没有问题。

这是代码的输出。

vector[0] :20
vector[1] :100
Base pointing: 20
Derived pointing: 32

1 个答案:

答案 0 :(得分:0)

int main(){
    std::vector<base *> vec;
    base A(20);
    derived B(32);

    vec.push_back(&A);
    vec.push_back(&B);

    for(unsigned int i=0; i < vec.size(); i++)
        cout << "vector[" << i << "] :" << vec[i]->getData() << endl;

    base * ptr;
    ptr = &A;
    cout << "Base pointing: " << ptr->getData() << endl;

    ptr = &B;
    cout << "Derived pointing: " << ptr->getData() << endl;

}

好吧,当我使用指针基矢量时,它会给出正确的值。谢谢你的回答。