1.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
class Vehicle
{
protected:
string NO;
public:
Vehicle(string str){
NO=str;
}
virtual void display()=0;
virtual ~Vehicle(){};
};
class Car:public Vehicle
{
int n;
double k;
public:
Car(string str,int num,double kg):Vehicle(str)
{
n=num;
k=kg;
}
virtual void display()
{
cout<<NO<<" "<<n*8+k*2<<endl;
}
};
class Truck:public Vehicle
{
double k;
public:
Truck(string str,double kg):Vehicle(str)
{
k=kg;
}
virtual void display()
{
cout<<NO<<" "<<k*5<<endl;
}
};
class Bus:public Vehicle
{
int n;
public:
Bus(string str,int num):Vehicle(str){n=num;}
virtual void display()
{
cout<<NO<<" "<<n*3<<endl;
}
};
int main()
{
Vehicle *pd[10];
string str;
int t,num,i=0;
double kg;
cin>>t;
while(t){
cin>>str;
if(t==1){
cin>>num>>kg;
pd[i]=new Car(str,num,kg);
}else if(t==2){
cin>>kg;
pd[i]=new Truck(str,kg);
}else if(t==3){
cin>>num;
pd[i]=new Bus(str,num);
}
pd[i]->display();
i++;
cin>>t;
}
delete *pd;
return 0;
}
2.
#include <iostream>
using namespace std;
const float pi = 3.14159;
class Shape
{
int m_ID;
public:
void getID(int id) { m_ID = id; }
int setID() { return m_ID; }
int getArea() { return 0; }
Shape(int i=0) { m_ID = i; cout << "Shape constructor called:" << m_ID << endl; }
~Shape() { cout << "Shape destructor called:" << m_ID << endl; }
};
class Circle :public Shape
{
int r;
public:
void getr(int i) { r = i; }
int setr() { return r; }
float getArea() { return pi * r * r; }
Circle(int newr, int newid) :r(newr), Shape(newid) { cout << "Circle constructor called:" << setID()<< endl; }
~Circle() { cout << "Circle destructor called:" << setID() << endl; }
};
class Rectangle :public Shape
{
int h, w;
public:
int getArea() { return h * w; }
int geth() { return h; }
void seth(int h1) { h = h1; }
int getw() { return w; }
void setw(int w1) { w = w1; }
Rectangle(int newh, int neww, int newid):h(newh),w(neww),Shape(newid) { cout << "Rectangle constructor called:" << setID() << endl; }
~Rectangle() { cout << "Rectangle destructor called:" << setID() << endl; }
};
int main()
{
Shape s(1);
Circle c(4, 2);
Rectangle r(4, 5, 3);
cout << "Shape的面积" << s.getArea() << endl;
cout << "Circle的面积" << c.getArea() << endl;
cout << "Rectangle的面积" << r.getArea() << endl;
}