C++中如何在一个构造函数中调用另一个构造函数
2015-06-08 17:55
381 查看
http://blog.chinaunix.net/uid-23741326-id-3385581.html
在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
可以看出,当前对象确实被改变了。
在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
可以看出,当前对象确实被改变了。
相关文章推荐
- C++中的Lambda表达式详解
- C++在Ubuntu上编译mysql问题
- C++——拼接+=
- C++ 调用webservice 出现 函数返回值为 3 (SOAP_TAG_MISMATCH) 的解决方案
- 多线程编程 c++ /thread(detach,join)/ _beginthreadex
- C++——字符串的拼接
- c++ pair类型
- 【Multiply Strings】cpp
- C++64位整型相乘取模的溢出处理(二)
- VS2010 C++ 操作Excel表格的编程实现
- 【C++】 VS2010 打开VS2012 新建的工程
- Effective C++学习笔记
- Effective C++学习笔记 分类: C/C++ 2015-06-08 16:52 27人阅读 评论(0) 收藏
- 线程池原理及创建(C++实现)
- vc++ 的指针和数组结合理解的最佳例子
- C/C++ 笔试、面试题目大汇总2
- 总结几个C语言中的坑(二)
- 总结几个C语言中的坑(二)
- C++第七章
- C++第五章