注册 登录
编程论坛 C++教室

类的对象作为函数参数而出现的问题

幽园香客 发布于 2007-03-24 22:06, 1640 次点击
将类的对象作为函数参数,测试时出现了奇怪的结果。
#include "iostream.h"
class test
{
public:
test(){cout<<"test construction"<<endl;}
~test(){cout<<"test destruction"<<endl;}
}
class A
{
public:
A(test s){cout<<"A construction"<<endl;}
~A(){cout<<"A destruction"<<endl;}
}
void main()
{
test a;
A(a);
return 0;
}
结果: test construction
A construction
test destruction //注意此行,多调用一次test析构函数
A destruction
test destrcution
这是怎么回事?难道析构函数和构造函数还不是配对出现的?哪位兄弟知道,谢谢了
8 回复
#2
song42007-03-24 22:20
以下是引用幽园香客在2007-3-24 22:06:24的发言:
将类的对象作为函数参数,测试时出现了奇怪的结果。
#include "iostream.h"
class test
{
public:
test(){cout<<"test construction"<<endl;}
~test(){cout<<"test destruction"<<endl;}
}
class A
{
public:
A(test s){cout<<"A construction"<<endl;} 是这个临时变量的析构函数以后要注意这个问题
// A(test& s){cout<<"A construction"<<endl;} 这样就是你要的
~A(){cout<<"A destruction"<<endl;}
}
void main()
{
test a;
A(a);
return 0;
}
结果: test construction
A construction
test destruction //注意此行,多调用一次test析构函数
A destruction
test destrcution
这是怎么回事?难道析构函数和构造函数还不是配对出现的?哪位兄弟知道,谢谢了

#3
zinking2007-03-24 22:26
嗯,试了一下确实有这个问题,查查C++的规范巴,才疏学浅没能解决,抱歉
#4
song42007-03-24 22:34
以下是引用zinking在2007-3-24 22:26:26的发言:
嗯,试了一下确实有这个问题,查查C++的规范巴,才疏学浅没能解决,抱歉

。。。
是我么
我没有编译器
(C++不会忘这么多吧)

#5
zinking2007-03-24 22:45

#include "iostream.h"
class test
{
public:
test(){cout<<"test construction"<<endl;}
test(test& t){cout << "test copy construction"<<endl;}
~test(){cout<<"test destruction"<<endl;}
};
class A
{
public:
A(test s){cout<<"A construction"<<endl;}
~A(){cout<<"A destruction"<<endl;}
};

int main()
{
test a;
A *b=new A(a);

delete b;

return 0;
}
你试一下就明白了

#6
zinking2007-03-24 22:46
仔细想了一下之后弄明白了
#7
song42007-03-24 22:53
test construction
test copy construction
A construction
test destruction
A destruction
test destruction

是这个吧
#8
yuyunliuhen2007-03-24 23:08
#9
幽园香客2007-03-25 10:28
谢谢楼上的几位版主!呵呵,昨天晚上可能是糊涂了,竟然忘了考虑默认拷贝构造函数了。

[此贴子已经被作者于2007-3-25 10:29:43编辑过]


1