下面我有一个特别的场景。 下面的代码应该打印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
如果函数foo
是base
中的虚函数,则对其进行多态调度; 多态性是指当您调用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);
你不需要初始化“它”吗? 我相信您应该这样做=listofas.begin(); 在开始插入之前。