gpt4 book ai didi

c++ - 多态对象列表

转载 作者:太空狗 更新时间:2023-10-29 21:27:21 25 4
gpt4 key购买 nike

我在下面有一个特定的场景。下面的代码应该打印 B 和 C 类的 'say()' 函数并打印 'B says..' 和 'C says...' 但它没有。任何想法..我正在学习多态性,所以也在下面的代码行中评论了一些与它相关的问题。

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();
return 0;
}

最佳答案

你的问题叫做切片,你应该检查这个问题:Learning C++: polymorphism and slicing

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

list<A*> listOfAs;

然后将这些 aBaC 指针插入到它,而不是创建它们所指向的对象的拷贝。您将元素插入列表的方式是错误的,您应该使用 push_back 函数来插入:

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

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

然后你的循环看起来像这样:

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

输出:

B Sayssss....
C Says

希望这对您有所帮助。

关于c++ - 多态对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com