多态对象列表
list of polymorphic objects
下面有一个特定的场景。下面的代码应该打印B和C类的"say()"函数,并打印"B says.."C说…"但事实并非如此。任何想法。。我正在学习多态性,所以在下面的代码行中也评论了一些与之相关的问题。
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;
}
您的问题被称为切片,您应该检查这个问题:学习C++:多态性和切片
您应该将此列表声明为指向A
S:的指针列表
list<A*> listOfAs;
然后插入这些指向它的aB
和aC
指针,而不是创建它们所指向的对象的副本。将元素插入列表的方式是错误的,您应该使用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
希望这能有所帮助。
虚拟类层次结构的多态性仅通过引用或指向基本子对象的指针起作用:
struct Der : Base { /* ... */ };
Der x;
Base & a = x;
a.foo(); // calls Der::foo() from x
如果函数CCD_ 5是CCD_;多态性是指当您调用类型为Base
的对象的成员函数时,实际被调用的函数可能在类Der
中实现。
容器只能存储固定类型的元素。为了存储多态集合,您可以使用一个指向基类的指针容器。由于您需要将实际对象存储在其他地方,因此生命周期管理是不平凡的,最好留给专用包装器,如unique_ptr
:
#include <list>
#include <memory>
int main()
{
std::list<std::unique_ptr<Base>> mylist;
mylist.emplace_back(new Der1);
mylist.emplace_back(new Der2);
// ...
for (p : mylist) { p->foo(); /* dispatched dynamically */ }
}
list::iterator it;
B bObj;
C cObj;
A *aB = &bObj;
A *aC = &cObj;
listOfAs.insert(it,*aB);
你不需要初始化"it"吗?我认为你应该这样做=listOfAs.begin();在开始插入之前。
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 从封装在对象中的函数 C++ 返回时为空的列表
- 如何在不销毁对象的情况下返回对象列表
- 如何使用Q_PROPERTY公开自定义对象列表
- 链接列表在 cpp 中包含不同的对象类
- 如何使用对象制作分数列表并获得平均值
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在Windows Media Foundation SDK中指定语言列表对象
- 在 DLL 中嵌入 Python:Py_DECREF列表对象时访问冲突读取位置
- 将类的每个实例添加到列表对象的构造函数
- 列表<对象*>迭代器中的分段错误
- 如何使用list::sort()对STL列表对象进行排序,同时将自定义排序函数作为参数传递给list::排序
- 如何防止客户端修改列表对象
- c++列表对象错误
- 在列表对象中使用对象的派生函数
- 编译器错误 使用列表<对象*的迭代器> C++