4 objects in existence after allocation 3 objects in existence after deletion
说明:这个程序使用静态数据成员追踪记载创建对象的个数。完成这一工作的方 法就是每创建一个对象就调用构造函数一次。每调用构造函数一次,静态 数据成员total就增加1,每撤消一个对象就调用析构函数一次。每调用析 构函数一次,静态数据成员total就减少1。 [4_15] 运行结果是: Here’s the program output. Let’s generate some stuff… Counting at 0 Counting at 1 Counting at 2 Counting at 3 Counting at 4 Counting at 5 Counting at 6 Counting at 7 Counting at 8 Counting at 9
说明:在程序中main()只包括了一个return语句,但竟然有内容输出!什么时候
调用了构造函数?构造函数在对象被定义时调用。那么对象anObject是何时被调用的呢?是在main()之前,语句”test anObject”处。因此,anObject的构造函数是先于main()被调用的。在main()之前的所有全局变量都是在main()开始之前就建立了的。应该尽可能避免使用
全局变量,因为全局变量有可能引起名称冲突,使程序的执行结果和预想的不一样。 [4_16] [4_17]构建一个类book,其中含有2个私有数据成员qu和price,建立一 个有5个元素的数组对象,将qu初始化为1~5,将price初始化为qu的10 倍。显示每个对象的qu*price 答案见下: #include
book(int a,int b)
{ qu=a; price=b; } void show_money()
{ cout<
int qu,price; }; main()
{ book ob[5]={ book(1,10),book(2,20),
book(3,30),book(4,40),book(5,50) }; //16题用下面语句 /*int i;
for(i=0;i<5;i++)
ob[i].show_money();
return 0;*/
//17题用下面的语句 int i; book *p; p=&ob[4]; for(i=0;i<5;i++)
{ p->show_money(); p--; }
return 0; }
[4_18]使用C++的 见书139页题 #include
toy(int p,int c) { price=p; count=c; }
void input(int p,int c); void compute(); void print(); private:
int price; int count; long total; };
void toy::input(int p,int c) { price=p; count=c; }
void toy::compute()
{ total=(long)price*count; } void toy::print()
{ cout<<\void main()
{ toy te(2,100);//测试构造函数 toy *ob;
ob=new toy[6]; ob[0].input(25,130); ob[0].input(25,130); ob[1].input(30,35);
ob[2].input(15,20); ob[3].input(25,120); ob[4].input(45,10); ob[5].input(85,65); for(int i=0;i<6;i++)
ob[i].compute(); // clrscr();
for(i=0;i<6;i++)
ob[i].print(); delete ob; }
[4_19]构建一个类stock 见书139页 答案如下: #include
{ strcpy(stockcode,\ }
stock(char code[],int q=1000,float p=8.98) { strcpy(stockcode,code); quan=q; price=p; }
void print(void)
{ cout<
cout<<\ } private:
char stockcode[SIZE]; int quan; float price; }; main() {
stock st1(\ st1.print(); stock st2;
char stockc[]=\ st2=stockc; st2.print(); return 0; }
说明:执行以下语句,可在定义对象的同时,给数据成员设置初值。但构造函数 的参数必须定义为缺省值: stock st2;
char stockc[]=”600002”; st2=stockc; st2.print();
定义不含第2和第3个参数的对象st2时,quan的值为1000,price的值 为8.98
[4_20]编写一个有关股票的程序,见书139页题 #include
class shen_stock; //深圳类 class shang_stock //上海类 { public:
shang_stock(int g,int s,int p); //构造函数
friend void shang_count(const shang_stock ss);//计算上海的
//股票总数 friend void count(const shang_stock ss,const shen_stock zs); //计算上海和深圳的股票总数 private:
int general; //普通股票个数 int st; //ST股票个数 int pt; //PT股票个数 };
shang_stock::shang_stock(int g,int s,int p)//构造函数 { general=g; st=s; pt=p; }
class shen_stock
{ int general; //普通股票个数 int st; //ST股票个数 int pt; //PT股票个数 public:
shen_stock(int g,int s,int p);//构造函数
friend void shen_count(const shen_stock es);//计算深圳的股票总数 friend void count(const shang_stock ss,const shen_stock zs); //计算上海和深圳的股票总数 };
shen_stock::shen_stock(int g,int s,int p)//构造函数 { general=g; st=s; pt=p;
相关推荐: