C++类和对象 简单编程题目
发布网友
发布时间:2022-05-04 11:22
我来回答
共1个回答
热心网友
时间:2022-06-21 11:04
#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;
}