对象向量 [英] vector of objects

查看:72
本文介绍了对象向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将对象添加到内容"向量,并在所有对象上使用 show().但是作为Base"的子对象(A,B)的对象表现得像Base"类型的对象,什么不是我的意图.看起来,我尝试使用虚函数但它不起作用.

I tried to add objects to the "content" vector, and use show() on all of them. But the objects that are children (A, B) of "Base" behave like they were of "Base" type, what is not my intention. As it seems, I tried to use virtual functions but it doesn't work.

我希望代码不言自明.

class Base {
    public:
        virtual void show() { cout << "Base "; }
};

class A : public Base {
    public:
        virtual void show() { cout << "A "; }
};

class B : public Base {
    public:
        virtual void show() { cout << "B"; }
};



vector<Base> content;

void add(Base &o) {
    content.push_back(o);
}

A test1;
B test2;

add(test1);
add(test2);

for (size_t i = 0; i < content.size(); i++) {
        collection[i].show(); // output is: Base Base instead of A B
}   

提前致谢.

推荐答案

vector<Base*> content; // <<

void add(Base *o) { // <<
    content.push_back(o);
}

A test1;
B test2;

add(&test1); // <<
add(&test2); // <<

for (size_t i = 0; i < content.size(); i++) {
        collection[i]->show(); // <<
}   

这篇关于对象向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆