实验七 静态成员与友元
一、实验目的和要求
1. 了解程序运行中变量的作用域、生存期和可见性; 2. 掌握类的静态数据成员与静态函数成员的实现方法; 3. 掌握类的友元关系来实现数据共享;
4. 掌握类的友元函数与友元类的的实现方法。 二、实验设备及分组
1. Windows 7以上操作系统;
2. Visual C++ 2015集成开发环境; 3. PC或台式电脑。 三、实验内容和步骤
1. 验证分析程序
(1)运行如下程序,观察变量x与y的值的变化。 源程序如下:
#include
int x = 1, y = 2; int main() {
cout << \
cout << \
cout << \ int x = 10, y = 20;
cout << \ cout << \ fun();
cout << \
cout << \
system(\ return 0; }
void fun() {
int y = 200;
cout << \}
(2)设计C++程序,解决王婆卖瓜问题。没卖一个瓜,记录该瓜的重量,所卖瓜的总重量和总数目;同时还允许退瓜。
源程序如下:
#include
using namespace std;
class watermelon {
private: double weight; static double total_weight; static int total_number;
public: watermelon(double w) { weight = w; total_weight += w; total_number++; }
~watermelon() { total_weight -= weight; total_number--; }
void disp() { cout << \ }
static void total_disp() { cout << \ cout << \ cout << \ } };
double watermelon::total_weight = 0.0; int watermelon::total_number = 0;
int main() { watermelon w1(2.1); w1.disp(); watermelon::total_disp();
watermelon w2(6.2); w2.disp(); watermelon::total_disp(); watermelon w3(20.6); w3.disp(); watermelon::total_disp(); system(\ return 0; }
(3)设计C++程序,其中含有3个类,CBank、BBank和GBank,即分别为中国银行类、工商银行类与农业银行类。每个类都包含一个私有数据balance,用于存放储户在改行的存款额,另有一个友元函数total用于计算储户在这3家银行中的总存款数,友元函数max用于计算储户在哪家银行中的存款数最大。
源程序如下:
#pragma warning(disable : 4996) #include
class CBank; class BBank; class GBank;
class CBank //中国银行类 { long int balance;
public: CBank() { balance = 0; } CBank(long int b) { balance = b; } void getbalance() { cout << \请输入中国银行存款数: \
cin >> balance; } friend void total(CBank, BBank, GBank); friend void max(CBank, BBank, GBank); };
class BBank //中国工商银行类 { long int balance;
public: BBank() { balance = 0; } BBank(long int b) { balance = b; } void getbalance() { cout << \请输入中国工商银行存款数: \ cin >> balance; } friend void total(CBank, BBank, GBank); friend void max(CBank, BBank, GBank); };
class GBank //农业银行类 { long int balance;
public: GBank() { balance = 0; } GBank(long int b) {
};
}
balance = b;
void getbalance() { cout << \请输入农业银行存款数: \ cin >> balance; }
friend void total(CBank, BBank, GBank); friend void max(CBank, BBank, GBank);
void total(CBank A, BBank B, GBank C) { cout << \总的银行存款数: \}
void max(CBank A, BBank B, GBank C) { long int max; char str[20]; if (A.balance > B.balance) { if (A.balance > C.balance) { max = A.balance; strcpy(str,\中国银行\ } else { max = C.balance; strcpy(str, \农业银行\ } } else { if (B.balance > C.balance) { max = B.balance; strcpy(str, \工商银行\ } else {
相关推荐: