5,
//几个类(Vehicle类 Car类 Streetwheel类 Brake类)有着必然的联系,设计类与实现
#include<iostream>
using namespace std;
class Vechile{
public:
virtual void function() = 0;
};
class Streetwheel{
public:
Streetwheel(int x):diameter(x){}
void getdiameter(){
cout<<"轮子直径为:"<<diameter<<endl;
}
private:
int diameter;
};
class Brake{
public:
void stop(){
cout<<"stop-----"<<endl;
}
};
class Car:public Vechile{
public:
Car():w(4){
}
virtual void function(){
cout<<"我是小汽车"<<endl;
w.getdiameter();
b.stop();
}
private:
Streetwheel w;
Brake b;
};
int main(){
Car c ;
c.function();
return 0;
}
6,
//一个基类 Shape,在基类的基础上继承写一个二维图形类,再继承写一个三维图形类,设计与实现
#include<iostream>
using namespace std;
class Shape{
public:
virtual void area()=0;
};
class towShape:public Shape{
public:
towShape(int l=0,int w=0):length(l),weight(w){}
virtual void area()
{
int s;
s = length*weight;
cout<<"s="<<s<<endl;
}
protected://把他设置为protected了,下面的继承triShape才能直接用,若设置为private,要在该类中声明一个public 函数getheight,getweight来获取到
int length;
int weight;
};
class triShape:public towShape{
public:
triShape(int l=0,int w=0,int h=0):height(h),towShape(l,w){//构造函数初始化的形式
}
virtual void area()
{ int v;
v = length*weight*height;
cout<<"v="<<v<<endl;
};
private:
int height;
};
int main(){
triShape t(1,2,3);
t.area();
return 0;
}