实验目录:点击打开链接
第一题:(有知识点)
1、写出类A的定义,通过类的静态成员来记录已经创建的A类的实例(对象)的个数,使得下面的程序:
void main()
{ A *pa=new A[10];
cout<<“thereare”<<pa->GetObjCount()<<“objects”<<endl;
delete []pa;
cout<<“thereare”<<A::GetObjCount()<<“objects”<<endl;
}
得到的输出为:
there are10 objects
there are 0 objects
#include<bits/stdc++.h>
using namespace std;
class A
{static int num;
public:A(){num++;} ~A(){num--;}static int GetObjCount(){return num;}};
int A::num=0;
int main()
{A *pa=new A[10];cout<<"there are "<<pa->GetObjCount()<<" objects"<<endl;delete []pa;cout<<"there are "<<A::GetObjCount()<<" objects"<<endl; //知识点:对象被消除仍可以访问return 0;
}
第二题:
2、补充下列程序(程序见下页幻灯片)。
定义一个boat类,含有weight数据成员。
定义该类的一个友元函数, 该函数能输出一个boat对象的重量。
#include<iostream>
using namespace std;
class Boat{int weight;
public:Boat(int w):weight(w){}friend void display_weight(Boat &a);
};
void display_weight(Boat &a)
{cout<<a.weight<<endl;
}
int main()
{Boat b(100);display_weight(b);return 0;
}
第三题:
3、写完整程序。
定义一个Boat类和Car类,均含有weight数据成员。
定义一个友元函数,该函数能输出一个Boat对象和一个Car对象的重量和。
提示:(1)友元函数可以定义成如下形式: (注意形参)
void display_weight(Boat &boat, Car &car)
(2)如果先定义Boat类,类中用friend对友元函数声明,friend void display_weight(Boat &boat ,Car &car);
这里会出现还未定义的Car类,因此,需要在定义Boat类之前需用class Car;对Car类进行声明
类似,如果先定义Car类,则需要对Boat类先进行声明
#include<iostream>
using namespace std;
class Car;
class Boat{int weight;
public:Boat(int w):weight(w){}friend void display_weight(Car &b,Boat &a);
};
class Car
{int weight;
public:Car(int w):weight(w){}friend void display_weight(Car &b,Boat &a);};
void display_weight(Car &b,Boat &a)
{cout<<a.weight+b.weight<<endl;
}
int main()
{Boat b(100);Car c(150);display_weight(c,b);return 0;
}
第四题:
4、编写函数,计算两个点之间的距离
定义一个point类。
定义该类的一个友元函数,该函数能计算两个点之间的距离(提示:该函数有两个point类型的形参)。
#include<bits/stdc++.h>
using namespace std; class Point
{double x,y;
public:Point(double i,double j){x=i;y=j;}friend void d(Point &p1,Point &p2);
};
void d(Point &p1,Point &p2)
{cout<<sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
int main()
{Point p1(3,4),p2(0,0);d(p1,p2);return 0;
}
第五题:
静态成员和静态成员函数应用
#include<bits/stdc++.h>
using namespace std; class Student
{double score;static double tot,cou;
public:int sscore(double s) //这样就不用数组了{score=s;tot+=s;cou++;} static double sum(){ cout<<tot<<endl;return tot;} static double ave(){return tot/cou;}
};
double Student::tot=0;
double Student::cou=0;
int main()
{int n;cout<<"请输入学生总人数:"<<endl;cin>>n;Student s;for(int i=0;i<n;i++){double a;cout<<"请输入第"<<i+1<<"个学生成绩:"<<endl;cin>>a;s.sscore(a);}cout<<"学生成绩总和:"<<s.sum()<<endl;cout<<"学生平均成绩:"<<s.ave()<<endl;return 0;
}