簡體   English   中英

C++編譯器錯誤基類問題

[英]C++ compiler error base class issue

我得到這個->

錯誤 - 類型 'Ship' 不是 'CruiseShip' 的直接基礎 -

我想不明白。 這是我假設發生錯誤的地方。 我不確定我應該如何調用基類?

CruiseShip::CruiseShip(string n, string y, int p) : Ship(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

發送文件

#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

您需要從 Ship 派生 CruiseShip:

class CruiseShip : public Ship {

這個:

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

是一個基類構造函數調用,但您還沒有從 Ship 派生 CruiseShip,但編譯器知道 Ship 是一個類類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM