C++中如何在一个构造函数中调用另一个构造函数

来源:互联网 发布:淘宝网哪些鞋店比较好 编辑:程序博客网 时间:2024/05/17 07:38


http://blog.chinaunix.net/uid-23741326-id-3385581.html


在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

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

0 0
原创粉丝点击