1. 程式人生 > >實驗六 類的繼承

實驗六 類的繼承

一、實驗目的:

瞭解繼承的作用,掌握三種不同的繼承方法,掌握派生類的設計方法。

二、實驗內容:

1.定義一個Rectangle類,它包含兩個資料成員length和width,以及用於求長方形面積的成員函式。再定義Rectangle的派生類Rectangular,它包含一個新資料成員height和用來求長方體體積的成員函式。在主函式中,使用兩個類,求某個長方形的面積和某個長方體的體積。

#include<iostream>

using namespace std;

class Rectangle

{

public :

       voidarea();

       voidsetareadata(double x,double y);

protected:

       doublelength;

       doublewidth;

};

void Rectangle::setareadata( double x,double y)

{

       length=x;

       width=y;

}

void Rectangle::area()

{

       doubles=length*width;

       cout<<"長方形的面積:"<<s<<endl;

}

class Rectangular:public Rectangle

{

public:

       voidvolume();

       voidsetvolumedata(double z);

protected :

       doubleheight;

};

void Rectangular ::setvolumedata(double z)

{

       height=z;

}

void Rectangular :: volume()

{

       doublev=length*width*height;

       cout<<"長方形的體積:"<<v<<endl;

}

void main()

{

       RectangleA;

       A.setareadata(1.1,1.1);

       A.area();

       RectangularB;

       B.setareadata(1.1,1.1);

       B.setvolumedata(2.0);

       B.volume();

}



2. 教材312頁程式設計題第1題。

#include<iostream>

#include<cstring>

#include<string>

using namespace std;

class Employee

{

public :

Employee(charSnumber[]="\0",char Sname[]="\0",double bSalary=2000)

{

strcpy(number,Snumber);

strcpy(name,Sname);

basicSalary=bSalary;

}

voidinput()

{

cout<<"編號:";

cin>>number;

cout<<"姓名:";

cin>>name;

}

voidprint()

{

cout<<"員工:"<<name<<"\t\t編號:"<<number<<"\t\t本月工資:"<<basicSalary<<endl;

}

protected:

charnumber[5];

charname[10];

doublebasicSalary;

};

class Salesman : public Employee

{

public:

Salesman(intsal=0)

{

sales=sal;

}

voidinput()

{

Employee::input();

cout<<"本月個人銷售額:";

cin>>sales;

}

voidpay()

{

salary=basicSalary+sales*commrate;

}

voidprint()

{

   pay();

cout<<"銷售員:"<<name<<"\t\t編號:"<<number<<"本月工資:"<<salary<<endl;

}

protected:

staticdouble commrate;

intsales;

doublesalary;

};

double Salesman::commrate=0.005;

class Salesmanager:public Salesman

{

public:

Salesmanager(doublejSalary=3000)

{

jobSalary=jSalary;

}

voidinput()

{

Employee::input();

cout<<"本月銷售額:";

cin>>sales;

}

voidpay()

{

pay();

cout<<"銷售經理:"<<name<<"\t\t編號:"<<number<<"\t\t本月工資:"<<salary<<endl;

}

private:

doublejobSalary;

};

int main()

{

cout<<"基本員工\n";

Employeep1;

p1.input();

p1.print();

cout<<"銷售員\n";

Salesmanp2;

p2.input();

p2.print();

cout<<"銷售經理\n";

Salesmanagerp3;

p3.input();

p3.print();

}