码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-08-25 14:48:04      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   div   log   sp   new   

在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             }
15 
16 
17             A(int x)
18             {
19                     printf("In A::(int x). x=%d\n", x);
20                     m_x=x;
21             }
22 
23     private:
24             int m_x;
25     };

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

 

[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             }
16 
17 
18             A(int x)
19             {
20                     printf("In A::(int x). x=%d\n", x);
21                     m_x=x;
22             }
23 
24 
25     private:
26             int m_x;
27     };
28 
29     #endif

 

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

 

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

 

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

 

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

标签:style   blog   color   使用   io   div   log   sp   new   

原文地址:http://www.cnblogs.com/Androider123/p/3934700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!