我想爲我的c + +類寫一些代碼。我正在使用eclipse。我很難理解問題中的一些說明。在C + +指針陣列
我創建了一個名爲Ship的基類,然後爲我的CruiseShip類和CargoShip類使用了繼承。
對於遊輪類,我奉命創建
,它覆蓋在基類中的打印功能打印功能。 CruiseShip 班級的打印功能應只顯示船名和乘客的最大號碼 。
並且類似地對於CargoShip類
重寫在基類的打印功能的打印功能。班級的打印功能應該只顯示船名和船的貨物容量。
我不確定在基類中「覆蓋」打印函數意味着什麼。
它也指示我
證明有船舶指針數組程序的類。數組 元素應使用動態分配的Ship, CruiseShip和CargoShip對象的地址進行初始化。然後程序應該遍歷數組,每個對象的打印函數調用 。
#include <iostream>
#include <string>
using namespace std;
class Ship
{
protected:
string ship_name;
int year_built;
public:
Ship()
{
ship_name="";
year_built=0;
}
void set_ship_name(string str)
{
ship_name=str;
}
void set_year(int y)
{
year_built=y;
}
int get_year()
{
return year_built;
}
string get_ship_name()
{
return ship_name;
}
void print(string, int)
{
cout<<"Ship name is "<<ship_name<<" and it was built in the year "<<year_built<<endl;
}
};
class CruiseShip: public Ship
{
private:
int max_passengers;
public:
CruiseShip()// :Ship(str,year)
{
max_passengers=0;
}
void set_passengers(int pass)
{
max_passengers=pass;
}
int get_passengers()
{
return max_passengers;
}
void print1(string, int)
{
cout<<"Ship name is "<<get_ship_name()<<" and max number of passengers are "<<max_passengers<<endl;
}
};
class CargoShip: public Ship
{
private:
int cargo_capacity_in_tons;
public:
CargoShip()//:Ship (str,year)
{
cargo_capacity_in_tons=0;
}
void set_capacity(int pass)
{
cargo_capacity_in_tons=pass;
}
int get_capacity()
{
return cargo_capacity_in_tons;
}
void print2(string, int)
{
cout<<"Ship name is "<<get_ship_name()<<" and its capacity is "<<cargo_capacity_in_tons<<" Tons."<<endl;
}
};
int main(){
CruiseShip ship1;
CargoShip ship2;
string ship_name1;
string ship_name2;
int year_built1;
int year_built2;
int max_passengers;
int cargo_capacity_in_tons;
cout<<"What is the name of the cruise ship?"<<endl;
cin>>ship_name1;
ship1.set_ship_name(ship_name1);
cout<<"What year was "<<ship_name1<<" built in?"<<endl;
cin>>year_built1;
ship1.set_year(year_built1);
cout<<"What is the maximum capacity of "<<ship_name1<<"?"<<endl;
cin>>max_passengers;
ship1.set_passengers(max_passengers);
//ship1.print(ship_name1, year_built1);
ship1.print1(ship_name1, max_passengers);
cout<<"What is the name of the cargo ship?"<<endl;
cin>>ship_name2;
ship2.set_ship_name(ship_name2);
cout<<"What year was "<<ship_name2<<" built in?"<<endl;
cin>>year_built2;
ship2.set_year(year_built2);
cout<<"What is the maximum capacity of "<<ship_name2<<" in tons?"<<endl;
cin>>cargo_capacity_in_tons;
ship2.set_capacity(cargo_capacity_in_tons);
ship2.print2(ship_name2, cargo_capacity_in_tons);
return 0;
}
「我使用eclipse作爲我的編譯器。」 Eclipse是一個IDE,而不是編譯器。 – MrEricSir
@MrEricSir的意思是說,你應該谷歌「虛擬功能的C + +」和「基類指針多態C++」大多數人不會幫助你在這裏B/C你沒有表現出努力研究這個問題。 – TriHard8
我不知道。我會編輯我的問題... @MrEricSir – redcardinal