Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1936379
  • 博文数量: 77
  • 博客积分: 2175
  • 博客等级: 大尉
  • 技术积分: 2491
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-20 20:49
个人简介

欢迎光临我的博客

文章分类

全部博文(77)

文章存档

2023年(1)

2018年(4)

2017年(1)

2016年(2)

2015年(2)

2013年(5)

2012年(29)

2010年(33)

分类: C/C++

2012-10-25 15:21:53

在C++中,一个类的构造函数没法直接调用另一个构造函数,比如:

点击(此处)折叠或打开

  1. #ifndef _A_H_
  2. #define _A_H_
  3. #include <stdio.h>
  4. #include <new>
  5. class A
  6. {
  7. public:
  8.         A()
  9.         {
  10.                 printf("In A::(). m_x=%d\n", m_x);
  11.                 A(0);
  12.                 printf("Out A::(). m_x=%d\n", m_x);

  13.         }


  14.         A(int x)
  15.         {
  16.                 printf("In A::(int x). x=%d\n", x);
  17.                 m_x=x;
  18.         }

  19. private:
  20.         int m_x;
  21. };

这里第11行的调用A(0);只是构建了一个A的临时对象,并没有调用A(int x)来初始化自己。其运行结果是:

点击(此处)折叠或打开

  1. [root@tivu25 utcov]# ./UTest.out
    In A::(). m_x=4268020
    In A::(int x). x=0
    Out A::(). m_x=4268020
可以看到尽管调用了A(0),m_x仍然没有改变,是4268020.
正确的方法是使用placement new:


点击(此处)折叠或打开

  1. //A.h
  2. #ifndef _A_H_
  3. #define _A_H_
  4. #include <stdio.h>
  5. #include <new>
  6. class A
  7. {
  8. public:
  9.         A()
  10.         {
  11.                 printf("In A::(). m_x=%d\n", m_x);
  12.                 new(this) A(0);
  13.                 printf("Out A::(). m_x=%d\n", m_x);

  14.         }


  15.         A(int x)
  16.         {
  17.                 printf("In A::(int x). x=%d\n", x);
  18.                 m_x=x;
  19.         }


  20. private:
  21.         int m_x;
  22. };

  23. #endif

第11行应为: new(this) A(0); 也就是用当前对象来调用构造函数A(int x)构建一个“新”对象。其运行结果是:

点击(此处)折叠或打开

  1. [root@tivu25 utcov]# ./UTest.out
  2. In A::(). m_x=4268020
  3. In A::(int x). x=0
  4. Out A::(). m_x=0

可以看出,当前对象确实被改变了。




《返璞归真--UNIX技术内幕》在全国各大书店及网城均有销售:

                         
                       




阅读(15916) | 评论(0) | 转发(5) |
给主人留下些什么吧!~~