返回信息流下面程序在linux和windows均编译通过,运行时a.i 显示没有被初始化。
请教下原因以及解决方法。
**************************************
#include <iostream>
using namespace std;
class A{
public:
A(int i){m = i; cout<<"who can explain"<<endl;}
A(){
A(5);
cout<<"what happened?"<<endl;
}
int m;
};
int main(){
A a;
cout<<a.m<<endl;
getchar();
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #8117同步于 2008/6/3
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
请教:构造函数调用重载的构造函数
zhaotong
2008/6/3镜像同步16 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
呃,原因想通咧:
好像等价于下面的代码,创建了一个临时变量。不知道理解的对不对?
A(){
A *p = new A(5);
cout<<p->m<<endl;
delete p;
}
证明代码:
#include <iostream>
using namespace std;
class A{
public:
A(int i){m = i; cout<<"A(int) is called"<<endl;}
A(){
A(5);
cout<<"A() is called"<<endl;
}
~A(){cout<<"~A is called"<<endl;}
int m;
};
int main(){
A a;
cout<<a.m<<endl;
return 0;
}
继续求怎样成功调用的解决方法。(*^__^*) 嘻嘻……
原来如此,学习了
【 在 PtwCJ (鲜的每日C|头像不是我,我是长毛贼~~) 的大作中提到: 】
: 他想考什么?
: 显示的调用构造函数确实是产生了一个临时变量
http://forum.byr.edu.cn/wForum/disparticle.php?boardName=CPP&ID=5608&pos=4
我回答过这个问题。
A(){
A(5); //只是一个临时的,只是输出,没有什么作用。
cout<<"what happened?"<<endl;
}
用
new (this)A(5);
就可以了
ls的这是new的一个高级用法,一般能不用就不用吧还是
【 在 noname (无名亡者) 的大作中提到: 】
: http://forum.byr.edu.cn/wForum/disparticle.php?boardName=CPP&ID=5608&pos=4
: 我回答过这个问题。
: A(){
: ...................
我估计是想考:怎样在构造函数中把临时变量返回,因为构造函数没有显示的返回值。
【 在 PtwCJ 的大作中提到: 】
: 他想考什么?
: 显示的调用构造函数确实是产生了一个临时变量
new (this)A(5);
赞这个。
【 在 noname 的大作中提到: 】
: http://forum.byr.edu.cn/wForum/disparticle.php?boardName=CPP&ID=5608&pos=4
: 我回答过这个问题。
: A(){
: ...................