const int MaxCats = 5;
Cat *CatHouse[MaxCats]; int i; for (i = 0; i
CatHouse[i] = new Cat(i); TelepathicFunction(); }
for ( i = 0; i
delete CatHouse[i]; TelepathicFunction(); }
return 0; }
void TelepathicFunction() {
cout << \}
程序运行输出:
There are 1 cats alive! There are 2 cats alive! There are 3 cats alive! There are 4 cats alive! There are 5 cats alive! There are 4 cats alive! There are 3 cats alive! There are 2 cats alive! There are 1 cats alive! There are 0 cats alive!
5-8 什么叫做友元函数?什么叫做友元类? 解:
友元函数是使用friend关键字声明的函数,它可以访问相应类的保护成员和私有成员。友元类是使用friend关数都是相应类的友元函数。
5-9 如果类A是类B的友元,类B是类C的友元,类D是类A的派生类,那么类B是类A的友元吗?类C是类A的解:
类B不是类A的友元,友元关系不具有交换性; 类C不是类A的友元,友元关系不具有传递性; 类D不是类B的友元,友元关系不能被继承。
5-10 静态成员变量可以为私有的吗?声明一个私有的静态整型成员变量。 解:
可以,例如: private:
static int a;
5-11 在一个文件中定义一个全局变量n,主函数main(),在另一个文件中定义函数fn1(),在main()中对n赋对n赋值,显示n最后的值。 解:
#include
void main() {
n = 20; fn1();
cout << \的值为\}
// fn1.h文件 extern int n; void fn1() { n=30; }
程序运行输出: n的值为30
5-12 在函数fn1()中定义一个静态变量n,fn1()中对n的值加1,在主函数中,调用fn1()十次,显示n的值。解:
#include
static int n = 0; n++;
cout << \的值为\}
void main() {
for(int i = 0; i < 10; i++) fn1(); }
程序运行输出: n的值为1 n的值为2 n的值为3 n的值为4 n的值为5 n的值为6 n的值为7 n的值为8 n的值为9
n的值为10
5-13 定义类X、Y、Z,函数h(X*),满足:类X有私有成员i,Y的成员函数g(X*)是X的友元函数,实现对X的类,其成员函数f(X*)实现对X的成员i加5,函数h(X*)是X的友元函数,实现对X的成员i加10。在一个文件中实现main()函数。 解:
#include \void main() { X x; Z z; z.f(&x); }
// my_x_y_z.h文件 #ifndef MY_X_Y_Z_H class X; class Y { void g(X*); };
class X {
private: int i; public: X(){i=0;}
friend void h(X*); friend void Y::g(X*); friend class Z; };
void h(X* x) { x->i =+10; } void Y::g(X* x) { x->i ++; } class Z { public:
void f(X* x) { x->i += 5; } };
#endif // MY_X_Y_Z_H 程序运行输出:无
5-14 定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的解: 源程序:
#include
private:
int weight; public:
Car(int j){weight = j;}
friend int totalWeight(Car &aCar, Boat &aBoat); };
class Boat {
private: int weight; public:
Boat(int j){weight = j;}
friend int totalWeight(Car &aCar, Boat &aBoat); };
int totalWeight(Car &aCar, Boat &aBoat) {
return aCar.weight + aBoat.weight; }
void main() {
Car c1(4); Boat b1(5);
cout << totalWeight(c1, b1) << endl; }
程序运行输出: 9
5-15 如果在类模板的定义中有一个静态数据成员,则在程序运行中会产生多少个相应的静态变量? 解:
这个类模板的每一个实例类都会产生一个相应的静态变量。