多态对象列表 [英] list of polymorphic objects

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

问题描述

我有一个特定的场景。下面的代码应该打印B和C类的'say()'函数并打印'B说..'和'C说...'但它不会。任何想法..
我正在学习多态因此也在下面的代码行上注释了几个与它相关的问题。

I have a particular scenario below. The code below should print 'say()' function of B and C class and print 'B says..' and 'C says...' but it doesn't .Any ideas.. I am learning polymorphism so also have commented few questions related to it on the lines of code below.

class A
{
public:
// A() {}
virtual void say() { std::cout << "Said IT ! " << std::endl; }
virtual ~A(); //why virtual destructor ?
 };

void methodCall() // does it matters if the inherited class from A is in this method
{

class B : public A{
public:
//  virtual ~B(); //significance of virtual destructor in 'child' class
virtual void say () // does the overrided method also has to be have the keyword  'virtual'
{ cout << "B Sayssss.... " << endl; }
};
class C : public A{
public:
//virtual ~C();
virtual void say () { cout << "C Says " << endl; }
};

list<A> listOfAs;
list<A>::iterator it;

# 1st scenario
B bObj; 
C cObj;
A *aB = &bObj;
A *aC = &cObj;

# 2nd scenario
//  A aA;
//  B *Ba = &aA;
//  C *Ca = &aA; // I am declaring the objects as in 1st scenario but how about 2nd   scenario, is this suppose to work too?

listOfAs.insert(it,*aB);
listOfAs.insert(it,*aC);

for (it=listOfAs.begin(); it!=listOfAs.end(); it++)
{
cout <<  *it.say()  << endl;
}
}

int main()
{
methodCall();
retrun 0;
}


推荐答案

>切片,您应该检查此问题:学习C ++:多态性和切片

您应该将此列表声明为指向 A 的指针列表:

You should declare this list as a list of pointers to As:

list<A*> listOfAs;

,然后插入这些 aB aC 指向它,而不是创建它们指向的对象的副本。将元素插入列表的方式是错误的,您应该使用 push_back 函数插入:

and then insert these aB and aC pointers to it instead of creating copies of objects they are pointing to. The way you insert elements into list is wrong, you should rather use push_back function for inserting:

B bObj; 
C cObj;
A *aB = &bObj;
A *aC = &cObj;

listOfAs.push_back(aB);
listOfAs.push_back(aC);

然后你的循环可能如下所示:

Then your loop could look like this:

list<A*>::iterator it;
for (it = listOfAs.begin(); it != listOfAs.end(); it++)
{
    (*it)->say();
}

输出:

B Sayssss....
C Says

希望这有助于。

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

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