C ++编译器错误基类问题

时间:2016-05-02 15:26:50

标签: c++ inheritance

我得到了这个 - >

  

错误类型'Ship'不是'CruiseShip'的直接基础 -

我无法理解。这是我假设发生错误的地方。我不确定我是否应该如何调用基类?

  

CruiseShip :: CruiseShip(字符串n,字符串y,int p):发货(n,y)

CruiseShip.cpp

#include "CruiseShip.h"
#include "Ship.h"

#include <iostream>

using namespace std;

Ship s;
  CruiseShip::CruiseShip(string n, string y, int p) : Ship(n,y)
  {
    passengers=p;
  }
  //A print function that overrides the print function in the base class.
  //The CruiseShip class's print function should display only the ship's
  //name and the maximum number of passengers.
   void print()
   {
    cout<<"Name: "<<s.getName()<<"\nMaximum passengers:"<<passengers<<endl;
  cout<<"-------------------------"<<endl;
   }

CruiseShip.h

#ifndef CRUISESHIP_H
#define CRUISESHIP_H
#include <string>
using namespace std;

class Ship;

class CruiseShip{
    private:
        int passengers;
        Ship::Ship s;
    public:
    CruiseShip(string, string, int);
    virtual void print();
};

#endif

Ship.cpp

#include "Ship.h"
#include <iostream>

using namespace std;

string name;
string built;

Ship::Ship(){

}
Ship::Ship(string n, string b)
{
   name = n;
  built = b;

}
//accessors and mutators methods
string getName()
{
  return name;
}
string getBuilt()
{
  return built;
}
//A virtual print function that displays
//the ship's name and the year it was built
void print()
{
  cout<<"Name:"<<getName()<<"\nYear built:"<<getBuilt()<<endl;
  cout<<"-------------------------"<<endl;
}

Ship.h

#ifndef SHIP_H
#define SHIP_H
#include <string> 

using namespace std;

class Ship{
private:
    string name;
    string built;

public:
    Ship();
    Ship(string, string);
    string getName();
    string getBuilt();
    virtual void print();


};
#endif

1 个答案:

答案 0 :(得分:2)

您需要从Ship派生CruiseShip:

class CruiseShip : public Ship {

这样:

CruiseShip::CruiseShip(string n, string y, int p) : Ship(n,y)
                                                  ^^^^^^^^^^^^

是基类构造函数调用,但您尚未从Ship派生CruiseShip,但编译器知道Ship是类类型。