实验目的:
- 理解派生类中成员与基类成员的关系
- 掌握派生类构造函数的定义和继承成员的初始化方法
- 掌握各类成员的访问控制特性及其使用方法
- 掌握公有继承的使用方法
- 掌握多继承的使用方法
- 掌握在继承方式下,构造函数与析构函数的执行顺序与构造规则。
- 掌握结合实际问题建立合理的类层次结构的能力
[实验任务二]:人与学生
设计一个类people,有保护数据成员:age(年龄,整型),name(姓名,string),行为成员:两个构造函数(一个无参,另一个有参数);析构函数;void setValue(int m, string str)给age和name赋值;void display()输出age和name。
设计一个学生类student,公有继承类people,有私有成员:ID(学号,整型),行为成员:两个构造函数(一个无参,另一个有参数);析构函数;void setID(int m)给ID赋值;void displayID()输出ID。
在main函数定义学生对象,给对象初始化赋值或调用setValue()和setID()赋值,并输出学生的信息。
#include<iostream>
#include<string>
using namespace std;
class People
{
protected:
int age;
string name;
public:
People() {}
~People() {}
People(string na, int ag)
{
age = ag;
name = na;
}
void setValue(int m, string str)
{
age = m;
name = str;
}
virtual void display() = 0;
};
class Student : public People
{
private:
int studentID;
public:
Student() {}
~Student() {}
Student(string na, int ag, int sID) :
People(na, ag)
{
studentID = sID;
}
void setID(int m)
{
studentID = m;
}
void display()
{
cout << name << " ";
cout << age << " ";
cout << studentID << endl;
}
};
class Teacher : public People
{
private:
int teacherID;
public:
Teacher() {}
~Teacher() {}
Teacher(string na, int ag, int tID) :
People(na, ag)
{
teacherID = tID;
}
void setID(int m)
{
teacherID = m;
}
void display()
{
cout << name << " ";
cout << age << " ";
cout << teacherID << endl;
}
};
int main()
{
string x, q; int y, z, w, e, z2, e2;
cout << "请输入学生和老师的姓名,年龄和学号" << endl;
cin >> x >> y >> z >> q >> w >> e;
Student st(x, y, z);
Teacher te(q, w, e);
cout << "修改前" << endl;
st.display();
te.display();
// 修改ID
cout << "请输入学生和老师修改后的id" << endl;
cin >> z2 >> e2;
st.setID(z2);
te.setID(e2);
cout << "\n修改后" << endl;
st.display();
te.display();
return 0;
}
[实验任务三]:以点类为基础设计图形类体系
首先定义点类,应包含 x,y 坐标数据成员,坐标获取及设置函数、显示函数和面积计 算函数等成员函数等; 以点类为基类派生圆类,增加表示半径的数据成员,半径获取及设置函数、周长计算函 数、重载显示函数和面积计算函数等;
实验要求:
1.注意加上必要的输入输出提示;
2.注意开头的标注部分,加上自己的姓名以及修改日期;
3.附上不少于3个的测试结果。
#include <iostream>
#include <cstring>
#include<math.h>
using namespace std;
class Point
{
private:
float a, b, x, y;
public:
Point(float x, float y);
~Point() { //析构函数
cout << "Destructor called" << endl;
}
float getX() {
cout << "x坐标为:" << x << endl;
return 0;
}
float getY() {
cout << "y坐标为:" << y << endl;
return 0;
}
};
class Circle :public Point
{
private:
double r;
double c;
public:
Circle(double i, double j, double k);
float getr(){
cout << "圆的半径为:" << r << endl;
return 0;
}
void calculate();
void calculate2();
};
Circle::Circle(double i, double j, double k) :Point(i, j), r(k) {}
Point::Point(float a, float b)
{
x = a;
y = b;
}
void Circle::calculate()
{
c = 3.14 * r * r;
cout << "面积:" << c << endl;
}
void Circle::calculate2()
{
double d;
d = 3.14 * 2 * r;
cout << "周长:" << d << endl;
}
int main()
{
float a, b, r;
cout << "请输入xy坐标值";
cin >> a >> b ;
Point p1(a, b);
p1.getX();
p1.getY();
cout << "请输入圆的半径";
cin >> r;
Circle c(a, b, r);
c.calculate();
c.calculate2();
}