本文介绍了C ++如何调用子类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用派生类 B :: display() C :: display(),但是它使用 A :: display().如何更改代码,以便可以调用派生类的 display() name 一起显示 id ?
在此先感谢:)

I want to use the derived class B::display() and C::display(), but it uses A::display(). How do I change the code so that I can call the derived class' display() to display the id together with name?
Thanks in advance :)

#include <iostream>
#include <vector>

using namespace std;

class A
{
protected :
    int id;
public:
    A ( int id = 0 ) : id(id) {}
    virtual void display() { cout << id << endl; }

};

class B : public A
{
    string name;
public:
    B ( int id = 0, string name = "-" ) : A(id), name(name) {}
    void display() { cout << id << " " << name << endl; }
};

class C : public A
{
    string name;
public:
    C ( int id = 0, string name = "-" ) : A(id), name(name) {}
    void display() { cout << id << " " << name << endl; }
};

int main()
{
    vector< vector <A> > aa;
    vector<A> bb ;
    vector<A> cc ;

    A *yy = new B(111, "Patrick");
    A *zz = new C(222, "Peter");
    bb.push_back(*yy);
    cc.push_back(*zz);

    aa.push_back(bb);
    aa.push_back(cc);

    for ( int i = 0; i < aa[0].size(); i++)
    {
        aa[0][i].display();
        aa[1][i].display();
    }
}

推荐答案

您的问题是,您声明的向量是非指针类型的,并且在运行时您丢失了指向子类的点",而您只留下了与超一流.您要做的就是将所有矢量更改为指针类型,如下所示:

your problem his that you are declartion of the vector is of non pointer type , and on runtime you are losing the "point" to the subclass and you just stay with the super class.all you have to do is change all of your vectors to pointer type , like that:

vector<A*> bb;

这篇关于C ++如何调用子类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:12