您的位置:首页 > 编程语言 > C语言/C++

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

2014-08-25 13:03 281 查看
在C++中,一个类的构造函数没法直接调用另一个构造函数,比如:

#ifndef _A_H_
#define _A_H_
#include <stdio.h>
#include <new>
class A
{
public:
A()
{
printf("In A::(). m_x=%d\n", m_x);
A(0);
printf("Out A::(). m_x=%d\n", m_x);

}

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

private:
int m_x;
};


这里第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:

//A.h
#ifndef _A_H_
#define _A_H_
#include <stdio.h>
#include <new>
class A
{
public:
A()
{
printf("In A::(). m_x=%d\n", m_x);
new(this) A(0);
printf("Out A::(). m_x=%d\n", m_x);

}

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

private:
int m_x;
};

#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


可以看出,当前对象确实被改变了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐