C ++如何调用子类函数

时间:2016-12-16 18:16:57

标签: c++ polymorphism subclass superclass

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

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

3 个答案:

答案 0 :(得分:2)

你的问题是你声明向量是非指针类型的,并且在运行时你正在失去对子类的“点”而你只是留在超类。 您所要做的就是将所有向量更改为指针类型,如:

vector<A*> bb;

答案 1 :(得分:1)

这里的问题是为了继承工作,你需要使用指针。你的向量是choice = input("fc; cf; fk;?") if (choice == 'fc'): def fc(): fahrenheit = int(input("enter temp: ")) celsius = (fahrenheit - 32) / 1.8 print(celsius) fc() elif (choice == 'cf'): def cf(): celsius = int(input("enter temp: ")) fahrenheit = (celsius * 1.8) + 32 print(fahrenheit) cf() elif (choice == 'fk'): def fk(): fahrenheit = int(input("enter temp: ")) kelvin = 5/9(fahrenheit - 32) + 273 print(kelvin) fk()而不是vector<A>所以当你推回yy和zz的解引用版本时,你推回他们的A数据成员的副本而不是B和C数据的副本成员。 B和C的大小与A不同,因此它只会复制适合A对象的数据成员。

http://www.learncpp.com/cpp-tutorial/125-the-virtual-table/

答案 2 :(得分:0)

你不能期望多态性在没有指针的情况下工作。 将主要部分更改为

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