实验三:类与对象(二)
实验三:类与对象(二)
实验目的
(1)进一步加深对类和对象的理解。
(2)掌握类的构造函数和析构函数的概念和使用方法。
(3)掌握组合类的定义和使用。
实验环境
1、 PC计算机一台;
2、 Dev-C++开发环境。
实验原理
实验内容
1、有如下程序,分析其执行过程,写出运行结果,增加一个函数foo,在函数中使用Employee类对象的引用(Employee&)作为形参,在main函数中调用foo函数实现某个功能。
2、定义矩形类如下:类中含有两个静态成员变量和一个静态成员函数,请将类中各函数定义完整,并在main函数中创建三个矩形对象,输出创建矩形的个数和总面积。
3、分析并解释下列程序的运行结果。
~~#include < iostream> ~~
实验代码及结果
1、----
#include<iostream>
using namespace std;
class Employee{
private:
int empid;
int empgrade;
float empsalary;
public:
Employee(int number,int n,float s):empid(number),empgrade(n),empsalary(s){
cout<<"赋值"<<endl;
}
void change(int n,float s){
cout<<"改变赋值"<<endl;
empgrade=n;
empsalary=s;
}
void display(){
cout<<"输出"<<endl;
cout<<empid<<" "<<empgrade<<" "<<empsalary<<endl;
}
void foo(Employee &p){
cout<<"调用复制构造"<<endl;
empgrade=p.empgrade;
empsalary=p.empsalary*2;//薪资的2倍
}
};
int main(){
Employee employee(2021001,3,89.98);
//调用Employee的构造函数,创建employee对象,并对employee进行赋值
employee.display();
//调用display函数输出结果
employee.change(5,99.99);
//调用change函数对employee对象中的empgrade,empsalary重新赋值
employee.display();
//调用display函数输出结果
employee.foo(employee);
//调用foo函数对employee对象中的empsalary重新赋值为(empsalary*2)
employee.display();
//调用display函数输出结果
system("pause");
return 0;
}
2、------
#include<iostream>
using namespace std;
class Rectangle{
private:
int width,height;
static int Areasum;
static int Number;
public:
Rectangle(int w,int h):width(w),height(h){
Areasum+=w*h;
Number++;
}
static void PrintToral(){
cout<<"矩形总个数:"<<Number<<" "<<"矩形总面积:"<<Areasum<<endl;
}
};
int Rectangle::Areasum=0;//初始化Areasum=0
int Rectangle::Number=0;//初始化Number=0
int main(){
Rectangle rectangle1(3,5);
rectangle1.PrintToral();
Rectangle rectangle2(3,5);
rectangle2.PrintToral();
Rectangle rectangle3(3,5);
rectangle3.PrintToral();
system("pause");
return 0;
}
3、-------
#include<iostream>
using namespace std;
const float pi=3.1415926;
class Circle
{
private:
float radius,x,y;
public:
Circle(float a,float b,float c){
radius=a;
x=b;
y=c;
}
Circle(float a){
cout<<"调用圆的构造函数"<<endl; // 1
radius=a;
x=0;
y=0;
}
Circle(Circle &a){
cout<<"调用圆的复制构造函数"<<endl; // 2 3 4 7
radius=a.radius;
x=a.x;
y=a.y;
}
float setr(float r){
radius=r;
}
float countperi();
float countarea();
Circle();
~Circle()
{
cout<<"调用圆的析构函数"<<endl; // 6
}
};
class Cylinder
{
private:
Circle y;
float h;
public:
Cylinder(Circle xy,float h1);
Cylinder(Cylinder &C);
float getvolumn()
{ return y.countarea()*h;}
};
Cylinder::Cylinder(Circle xy,float h1):y(xy){
cout<<"调用圆柱体的构造函数"<<endl;// 5
h=h1;
}
Cylinder::Cylinder(Cylinder &C):y(C.y){
cout<<"调用圆柱体的复制构造函数"<<endl;// 8
h=C.h;
}
float Circle::countperi(){
return 2*pi*radius;
}
float Circle::countarea() {
return pi*radius*radius;
}
int main()
{
float peri,area,volumn;
Circle AA(1);
Circle DD(AA);
Cylinder BB(AA,2);
Cylinder CC(BB);
system("pause");
return 0;
}
//构造函数是一种特殊的类成员函数,是当创建一个类的对象时,它被调用来对类的数据成员进行初始化和分配内存。