C++实验: 类和对象(二)
1.实验目的
(1)进一步加深对类和对象的理解。
(2)掌握类的构造函数和析构函数的概念和使用方法。
(3)掌握对象数组、对象的指针及其使用方法。
(4)掌握友元的概念与使用。
(5)了解类模板的使用方法。
2.实验内容
(1)修改已知程序,增加一个fun函数,在main函数中调用,同时在fun函数中调用display与change函数,使用对象的引用(Student&)做形参;
(2)编写程序,使用静态数据成员与静态成员函数,计算出此商品的总销售款sum与每件商品的平均售价;
(3)分析已知程序,改变display函数位置,引用私有数据,输出时间,注意友元函数的作用;
(4)运行已知程序,体会类模板的作用,将其改写为在类模板外定义各成员函数。
3.实验代码
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n,float
s):num(n),score(s){
}
void change(int n,float s){
num=n,score=s;}
void display(){
cout<<num<<" "<<score<<endl;}
private:
int num;
float score;
};
int main()
{
Student
stud(101,78.5);
void fun(Student &);
fun(stud);
return 0;
}
void fun(Student
&stu)
{
stu.display();
stu.change(101,80.5);
stu.display();
}
(2)
#include <iostream>
using namespace std;
class Product
{
public:
Product(int