面向对象程序设计C++课后题答案 联系客服

发布时间 : 星期六 文章面向对象程序设计C++课后题答案更新完毕开始阅读3296727c31b765ce05081489

class CTest { public: CTest() { x=20; } void use_this(); private: int x; };

void CTest::use_this() { CTest y,*pointer;

this=&y; //错误,不能对this直接赋值

*this.x=10; //错误,按优先级原句的含义是*(this.x)=10,显然不对,正确的写 //法是(*this).x=10;或this->x=10; pointer=this; pointer=&y; }

void main() { CTest y;

this->x=235; //错误,this的引用不能在外部函数中,只能在内部函数中。 }

[4_12]答:运行结果是: 10,20 30,48 50,68 70,80

29

90,16 11,120

[4_13]答:运行结果是: Constructing 10 Destructing. 100 Destructing

[4_14]答:运行结果是: 3 objects in existence

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

30

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 class book { public:

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),

31

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 //#include class toy { public: toy(){ } toy(int p,int c) { price=p; count=c;

32