简体   繁体   English

在派生类中调用虚函数

[英]Calling virtual function in derived class

I have 2 classes. 我有2节课。 The base class has a virtual display function and member variable shipname and date. 基类具有虚拟显示功能以及成员变量的名称和日期。 The display() function in the base class prints the ship name. 基类中的display()函数将打印出船名。 The derived class has an override of display() which also prints the ship name and a member variable y. 派生类具有对display()的覆盖,该覆盖还将显示船名和成员变量y。

void Ship::display(){
    cout << shipName << endl << manufactureDate < <endl;
}

void CruiseShip::display(){
    cout << shipName << maxNoOfPassengers << endl;
}

I have a loop that calls an object from base class and object from derived class but it outputs only one ship name instead of two 我有一个循环,它调用基类中的对象和派生类中的对象,但是它只输出一个船名而不是两个

When I call display from derived class I the ship name is empty, but when I call it from base object it returns its value. 当我从派生类调用display时,船名是空的,但是当我从基础对象中调用它时,它将返回其值。

void main(){
    Ship       sh;
    CruiseShip cruShip;
    CargoShip  cargShip;

    sh.setName("Monster");
    sh.setDate("11/11/2011");
    cruShip.setNoOfPassengers(10);
    cargShip.setCapacity(1000);
    /*Ship *x[3] = {&sh, &cruShip, &cargShip};
    for(int i=0;i<3;++i){
        x[i]->display();
    }*/
    cout<<sh.getName()<<endl;
     cout<<cruShip.getName()<<endl;
     cout<<cargShip.getName();

    system("pause");
}

Monster shows only from object sh 怪物只显示对象sh

You are not setting the attributes of your cargShip object. 您未设置cargShip对象的属性。 You set the name and date of the sh object , but the cargShip object is a whole separate object, with its own name and date that you have not set yet. 您设置了sh 对象的名称和日期,但是cargShip 对象是一个完整的单独对象,具有您自己尚未设置的名称和日期。 Try: 尝试:

cargShip.setName("Cargo Ship")
cargShip.setCapacity(1000);

First of all it is not clear how the classes are defined, whether you initialize data members of the base class in the constructor of the derived class or not. 首先,不清楚是否定义类,是否在派生类的构造函数中初始化基类的数据成员。 Also I do not see that function display declared as virtual. 我也看不到该函数显示声明为虚拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM