C++类和对象 简单编程题目
开发一个交通工具Vechile的层次体系。创建四个类Vechile、Ship、Car、Truck。(1)Vechile类有名称、颜色、型号三个属性,有print()和ho...
开发一个交通工具Vechile 的层次体系。创建四个类Vechile 、Ship 、Car、Truck 。
(1) Vechile 类有名称、颜色、型号三个属性,有print()和horn()// 鸣笛 两个方法
(2 ) Ship 和car 从vechile 类继承而来,Truck 从Car 继承而来
(3 ) 实例化的派生类对象插入到一个Vechile 容器中,对于容器内的每个对象,输出
喇叭声和基本信息。
接下来40分钟内给出答案再加15分 展开
(1) Vechile 类有名称、颜色、型号三个属性,有print()和horn()// 鸣笛 两个方法
(2 ) Ship 和car 从vechile 类继承而来,Truck 从Car 继承而来
(3 ) 实例化的派生类对象插入到一个Vechile 容器中,对于容器内的每个对象,输出
喇叭声和基本信息。
接下来40分钟内给出答案再加15分 展开
1个回答
展开全部
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Vechile
{
public:
virtual void print(){
cout << endl
<< "Name: " << name << endl
<< "Color: " << color << endl
<< "Type: " << type << endl;
}
virtual void horn() = 0;
protected:
string name;
string color;
string type;
};
class Ship : public Vechile
{
public:
Ship( string n, string c, string t ){
name = n;
color = c;
type = t;
}
~Ship(){}
void horn(){
cout << "Ship~" << endl;
}
};
class Car : public Vechile
{
public:
Car( string n, string c, string t ){
name = n;
color = c;
type = t;
}
~Car(){}
void horn(){
cout << "Car~" << endl;
}
};
class Truck : public Car
{
public:
Truck( string n, string c, string t ) : Car( n, c, t ){}
~Truck(){}
void horn(){
cout << "Truck~" << endl;
}
};
int main()
{
vector<Vechile*> vec( 3 );
vec[0] = new Ship( "ship", "white", "123" );
vec[1] = new Car( "car", "black", "456" );
vec[2] = new Truck( "truck", "blue", "789" );
for ( int i = 0; i < 3; i++ )
{
vec[i] -> print();
vec[i] -> horn();
}
return 0;
}
#include <vector>
#include <string>
using namespace std;
class Vechile
{
public:
virtual void print(){
cout << endl
<< "Name: " << name << endl
<< "Color: " << color << endl
<< "Type: " << type << endl;
}
virtual void horn() = 0;
protected:
string name;
string color;
string type;
};
class Ship : public Vechile
{
public:
Ship( string n, string c, string t ){
name = n;
color = c;
type = t;
}
~Ship(){}
void horn(){
cout << "Ship~" << endl;
}
};
class Car : public Vechile
{
public:
Car( string n, string c, string t ){
name = n;
color = c;
type = t;
}
~Car(){}
void horn(){
cout << "Car~" << endl;
}
};
class Truck : public Car
{
public:
Truck( string n, string c, string t ) : Car( n, c, t ){}
~Truck(){}
void horn(){
cout << "Truck~" << endl;
}
};
int main()
{
vector<Vechile*> vec( 3 );
vec[0] = new Ship( "ship", "white", "123" );
vec[1] = new Car( "car", "black", "456" );
vec[2] = new Truck( "truck", "blue", "789" );
for ( int i = 0; i < 3; i++ )
{
vec[i] -> print();
vec[i] -> horn();
}
return 0;
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询