1、设计包含静态数据成员的类
某商店经销一种货物,货物成箱进,成箱卖出,购进和卖出都是以重量为单位(每箱的重量不同),商店需要记录下存货的总重量。
分析:
定义一个货物类,类中包含
私有成员 weight
一个静态数据成员total_weight;
在构造函数中,修改total_weight的值
在析构函数中,修改total_weight的值
在主函数中进行测试
#include<iostream>
using namespace std;
class Goods
{
double weight;
static double total_weight;
public:
Goods()
{
cout << "请输入改变的重量:" << endl;
cin >> weight;
total_weight = total_weight + weight;
cout << "进货后的重量:" << endl;
cout << total_weight << endl;
}
~Goods()
{
total_weight = total_weight - weight;
cout << "再销售后的重量:" << endl;
cout << total_weight << endl;
}
void print()
{
cout << total_weight << endl;
}
};
double Goods::total_weight = 100;
int main()
{
cout << "初始重量为100:" << endl;
Goods();
return 0;
}
2、写出类A的定义,通过类的静态成员来记录已经创建的A类的实例(对象)的个数,使得下面的程序:
void main()
{A *pa=new A[10];
cout<<“there are”<GetObjCount()<<“objects”<<endl;
delete []pa;
cout<<“there are”<<A::GetObjCount()<<“objects”<<endl;
}
得到的输出为:
there are 10 objects
there are 0 objects
定义一个boat类,含有weight数据成员。
定义该类的一个友元函数, 该函数能输出一个boat对象的重量。
//第一部分
#include<iostream>
using namespace std;
class A
{
private:
static int cout;
public:
A()
{
cout++;
}
~A()
{
cout--;
}
static int GetObjCount()
{
return cout;
}
};
int A::cout = 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;
}
//第二部分
#include<iostream>
using namespace std;
class Boat {
int weight;
public:
Boat()
{
cin >> weight;
}
friend void get(Boat &B)
{
cout << "输出:" << endl;
cout << B.weight << endl;
}
};
int main()
{
cout << "请输入重量:" << endl;
Boat boat;
get(boat);
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()
{
cout << "请输入船的重量:" << endl;
cin >> weight;
}
friend void display_weight(Boat& boat, Car& car);
};
class Car {
int weight;
public:
Car()
{
cout << "请输入汽车的重量" << endl;
cin >> weight;
}
friend void display_weight(Boat& boat, Car& car);
};
void display_weight(Boat& boat, Car& car)
{
cout << "二者重量和为:" << endl;
cout<<boat.weight + car.weight<<endl;
}
int main()
{
Boat B;
Car C;
display_weight(B, C);
return 0;
}
4、编写函数, 计算两个点之间的距离
定义一个point类。
定义该类的一个友元函数,该函数能计算两个点之间的距离(该函数有两个point类型的形参)。
#include<iostream>
#include<cmath>
using namespace std;
class Point
{
int x, y;
public:
Point()
{
cout << "请输入点的坐标(x,y):" << endl;
cin >> x >> y;
}
friend void calculate(Point& a, Point& b)
{
cout << "两点间的距离为:" << endl;
cout << sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
};
int main()
{
Point A, B;
calculate(A, B);
return 0;
}
实验心得:
本次实验练习了含静态数据成员的类和友元函数的使用。在写代码的过程中,在传参的时候出现错误,是我的参数形式掌握得不够。继续加油吧!