(1)掌握派生类的定义和实现方法;
(2)根据要求正确定义基类和派生类;
(3)根据要求正确定义虚函数;
(1)人员类、员工类、员工表类的定义和实现,并设计主程序进行测试。
(2)图形类、点类、长方形类、正方形类的定义和实现,并设计主程序进行测试。
(3)火炮类、战车类、坦克类的定义和实现,并设计主程序进行测试。
(1)员工类从人员类中派生,人员类和员工类的属性和方法设计合理。
(2)图形类为抽象类,提供统一的接口。
(3)长方形类和正方形类中实现图形类的接口。
(3)坦克类从火炮类和战车类派生。
(1)人员类派生:
#include
#include
using namespace std;
class Person
{
public:
Person(int, string, int);
void display();
private:
int num;
string name;
int age;
};
Person::Person(int n, string nam, int ag)
{
num = n;
name = nam;
age = ag;
}
void Person::display()
{
cout << endl << "num:" << num << endl;
cout << "name:" << name << endl;
cout << "age:" << age << endl;
}
class Worker :public Person
{
public:
Worker(int, string, int, float);
void display();
private:
float salary;
};
Worker::Worker(int n,string nam,int ag,float s):Person(n,nam,ag),salary(s){}
void Worker::display()
{
Person::display();
cout << "Salary:" << salary << endl;
}
int main()
{
Person per1(1001, "Li", 25);
Worker wor1(2001, "Wang", 24, 1500);
Person*pt = &per1;
pt->display();
pt = &wor1;
pt->display();
system("pause");
return 0;
}
运行截图:
(2)图形类接口:
#include
using namespace std;
// 基类
class Shape
{
public:
// 提供接口框架的纯虚函数
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// 派生类
class Rectangle : public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Square : public Shape
{
public:
int getArea()
{
return (width * width);
}
};
int main(void)
{
Rectangle Rect;
Square Squ;
Rect.setWidth(5);
Rect.setHeight(7);
// 输出对象的面积
cout << "长方形面积: " << Rect.getArea() << endl;
Squ.setWidth(5);
Squ.setHeight(7);
// 输出对象的面积
cout << "正方形面积: " << Squ.getArea() << endl;
system("pause");
return 0;
}
运行截图:
(3)多重继承:
#include
#include
using namespace std;
class Chariot //战车类
{
public:
Chariot(string nam, int w)
{
name = nam;
weight = w;
}
void display()
{
cout << "车体名称:" << name << endl;
cout << "车体重量:" << weight << endl;
}
protected:
string name;
int weight;
};
class Gun //火炮类
{
public:
Gun(float ca, string na)
{
caliber = ca;
gun_name = na;
}
void display()
{
cout << "火炮种类:" << gun_name << endl;
cout << "火炮口径:" << caliber << endl;
}
protected:
string gun_name;
float caliber;
};
class Tank :public Chariot, public Gun
{
public:
Tank(string nam,int w,float ca,string na,float m):Chariot(nam,w),Gun(ca,na),money(m){}
void show()
{
cout << "车体名称:" << name << endl;
cout << "车体重量:" << weight << endl;
cout << "火炮种类:" << gun_name << endl;
cout << "火炮口径:" << caliber << endl;
cout << "造价:" << money << "万元"<
运行结果: