作业
1. 编写一个圆类Circle,该类拥有:
① 1个成员变量,存放圆的半径;
② 两个构造方法
Circle( ) // 将半径设为0
Circle(double r ) //创建Circle对象时将半径初始化为r
③ 三个成员方法
double getArea( ) //获取圆的面积
double getPerimeter( ) //获取圆的周长
void show( ) //将圆的半径、周长、面积输出到屏幕
2. 编写一个圆柱体类Cylinder,它继承于上面的Circle类,还拥有:
① 1个成员变量,圆柱体的高;
② 构造方法
Cylinder (double r, double h) //创建Circle对象时将半径初始化为r
③ 成员方法
double getVolume( ) //获取圆柱体的体积
void showVolume( ) //将圆柱体的体积输出到屏幕
编写应用程序,创建类的对象,分别设置圆的半径、圆柱体的高,
计算并分别显示圆半径、圆面积、圆周长,圆柱体的体积。
3. 构建一个类person,包含字符串成员name(姓名),整型数据成员age(年龄),成员函数
display()用来输出name和age。构造函数包含两个参数,用来对name和age初始化。
构建一个类employee由person派生,包含department(部门),实型数据成员salary(工资),
成员函数display()用来输出职工姓名、年龄、部门、工资,其他成员根据需要自己设定。
主函数中定义3个employee类对象,内容自己设定,将其姓名、年龄、部门、工资输出,
并计算他们的平均工资。
解答
// 01, 02
// hw1.hh
#include <iostream>
#define pi 3.1415926
using namespace std;
class Circle
{
public:
Circle()
:_r(0)
{}
Circle(double r)
:_r(r)
{}
~Circle()
{ cout << "~Circle()" << endl; }
public:
double getArea();
double getPerimeter();
void show();
protected:
double _r;
};
class Cylinder
:public Circle
{
public:
Cylinder()
:_h(1)
{}
Cylinder(double r, double h)
: Circle(r)
,_h(h)
{}
~Cylinder()
{ cout << "~Cylinder()" << endl; }
public:
double getVolume();
void showVolume();
private:
double _h;
};
// hw1.cc
#include "hw1.hh"
double Circle::getArea()
{
return pi*_r*_r;
}
double Circle::getPerimeter()
{
return 4*pi*_r;
}
void Circle::show()
{
cout << "radio = " << _r << endl
<< "Perimeter = " << getPerimeter() << endl
<< "Area = " << getArea() << endl;
}
double Cylinder::getVolume()
{
return getArea()*_h;
}
void Cylinder::showVolume()
{
cout << "Cylinder::Volume = " << getVolume() << endl;
}
// test.cc
#include "hw1.hh"
void test()
{
Circle c1(2);
c1.show();
}
void test2()
{
Cylinder c2(2,1);
c2.showVolume();
}
int main()
{
test();
test2();
}
// .hh
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
Person(string name, int age)
:_name(name)
,_age(age)
{}
~Person()
{ cout << "~Person" << endl; }
void display()
{
cout << "Person:name = " << _name << endl
<< "Person:age = " << _age << endl;
}
protected:
string _name;
int _age;
};
class Employee
:public Person
{
public:
Employee(string name, int age, string dep, double sal)
:Person(name,age)
,_department(dep)
,_salary(sal)
{}
~Employee()
{ cout << "~Employee" << endl; }
void display()
{
cout << "Emp:name : " << _name << endl
<< "Emp: age : " << _age << endl
<< "Emp: dep : " << _department << endl
<< "Emp: sal : " << _salary << endl;
}
private:
string _department;
double _salary;
};
// test.cc
#include "Person.hh"
void test()
{
Person p1("Robben", 15);
p1.display();
}
void test2()
{
Employee e1("Robben", 15, "Boss", 99999999.00);
Employee e2("Tom", 12, "assis", 22223.00 );
Employee e3("Bob", 12, "saler", 23232.00 );
e1.display();
e2.display();
e3.display();
}
int main()
{
test2();
return 0;
}