一、实验目的
(1)进一布加深对类和对象的理解
(2)掌握类的构造函数和析构函数的概念和使用方法
(3)掌握对对象数组、对象指针及其使用方法
(4)掌握友元的概念和使用
(5)了解类模版的使用方法
二、实验内容
(1)类的构造函数和析构函数
#include<iostream>
usingnamespacestd;
classStudent
{
public:
Student(intn,floats):num(n),score(s){}
voidchange(intn,floats) {num=n; score=s;}
voiddisplay(){cout<<num<<" "<<score<<endl;}
private:
intnum;
floatscore;
};
voidfun(Student &stud)
{
stud.display();
stud.change(101,80.5);
stud.display();
}
intmain()
{
Student stud(101,78.5);//引用对象作为参数
fun(stud);
return0;
}
()类的应用——商店销售商品
#include<iostream>
usingnamespacestd;
classProduct
{
public:
Product(intn,intq,floatp) : num(n), quantity(q), price(p){};
voidtotal();//计算商品总价格
staticfloataverage();//计算每件商品平均价格
staticvoiddisplay();
private:
intnum;//销货员号
intquantity;//销货件数
floatprice;//销货单价
staticintn;//商品销售总件数
staticfloatsum;//总销售款
staticfloatdiscount;//折扣
};
voidProduct :: total()
{
floatrate = 1.0;
if(quantity > 10)
rate = 0.98 * rate;
sum = sum + quantity * price *rate *(1 - discount);
n = n + quantity;
}
floatProduct::average()
{
return(sum/n);
}
voidProduct ::display()
{
cout <<"Sum: "<< sum << endl;
cout <<"Average: "<< average() << endl;
}
floatProduct::discount=0.05;
floatProduct::sum=0;
intProduct::n=0;
intmain()
{
Product prod[3] = {
Product(101,5,23.5),Product(102,12,24.56),Product(103,100,21.5)
};
for(inti=0;i<3;i++)
prod[i].total();
Product::display();
cout <<"Hello"<< endl;
return0;
}
(2)友元函数的概念和使用
#include<iostream>
usingnamespacestd;
classDate;//对Date类的提前引用声明
classTime//定义Time类
{
public:
Time(int,int,int);
friendvoiddisplay(constDate &,constTime &);//友元函数
private:
inthour;
intminute;
intsec;
};
Time::Time(inth,intm,ints)// Time类的构造函数
{
hour=h;
minute=m;
sec=s;
}
classDate//定义Date类
{
public:
Date(int,int,int);
friendvoiddisplay(constDate &,constTime &);//友元函数
private:
intmonth;
intday;
intyear;
};
Date::Date(intm,intd,inty)// Date类的构造函数
{
month=m;
day=d;
year=y;
}
voiddisplay(constDate &d,constTime &t)
{
cout<<d.month<<"/"<<d.day<<"/"<<d.year<<endl;
cout<<t.hour<<":"<<t.minute<<":"<<t.sec<<endl;
}
intmain()
{
Time t1(10,13,56);
Date d1(12,25,2004);
display(d1,t1);
return0;
}
(3)类模版的使用
#include<iostream>
usingnamespacestd;
template<classnumtype>
classCompare
{
public:
Compare(numtype a, numtype b)
{
x = a;
y = b;
}
numtype max()
{
return(x > y) ? x : y;
}
numtype min()
{
return(x < y) ? x : y;
}
private:
numtype x, y;
};
intmain()
{
Compare <int> cmp1(3,7);
cout<<cmp1.max()<<" is the Maximum of two integer numbers."<<endl;
cout<<cmp1.min()<<" is the Minimum of two integer numbers."<<endl<<endl;
Compare <float> cmp2(45.78, 93.6);
cout<<cmp2.max()<<" is the Maximum of two float numbers."<<endl;
cout<<cmp2.min()<<" is the Minimum of two float numbers."<<endl<<endl;
Compare <char> cmp3('a','A');
cout<<cmp3.max()<<" is the Maximum of two characters."<<endl;
cout<<cmp3.min()<<" is the Minimum of two characters."<<endl;
return0;
}
三、实验结果及分析
通过这次实验,进一布加深对类和对象的理解、掌握类的构造函数和析构函数的概念和使用方法、掌握对对象数组、对象指针及其使用方法、掌握友元的概念和使用、了解类模版的使用方法。