科技时代新浪首页 > 科技时代 > 软件 > 正文

面对大型程序:C/C+语言struct深层探索(5)


http://www.sina.com.cn 2005年08月12日 18:42 太平洋电脑网

  文/宋宝华

    4. struct编程注意事项

  看看下面的程序:

1. #include <iostream.h>

2. struct structA
3. {
4. int iMember;
5. char *cMember;
6. };

7. int main(int argc, char* argv[])
8. {
9. structA instant1,instant2;
10.char c = 'a';
   
11. instant1.iMember = 1;
12. instant1
.cMember = &c;
 
13.instant2 = instant1;
 
14.cout << *(instant1.cMember) << endl;
 
15.*(instant2.cMember) = 'b';
 
16. cout << *(instant1.cMember) << endl;
 
17. return 0;
}

  14行的输出结果是:a
  16行的输出结果是:b

  Why?我们在15行对instant2的修改改变了instant1中成员的值!

  原因在于13行的instant2 = instant1赋值语句采用的是变量逐个拷贝,这使得instant1和instant2中的cMember指向了同一片内存,因而对instant2的修改也是对instant1的修改。

  在C语言中,当结构体中存在指针型成员时,一定要注意在采用赋值语句时是否将2个实例中的指针型成员指向了同一片内存。

  在C++语言中,当结构体中存在指针型成员时,我们需要重写struct的拷贝构造函数并进行“=”操作符重载。

[上一页] [1] [2] [3] [4] [5]



评论】【应用软件】【收藏此页】【 】【多种方式看新闻】【下载点点通】【打印】【关闭

爱问 iAsk.com



科技时代意见反馈留言板 电话:010-82628888-5828   欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

Copyright © 1996 - 2005 SINA Inc. All Rights Reserved

版权所有 新浪网