首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

函数返回一个对象解决办法

2012-02-13 
函数返回一个对象有以下代码#includeiostream#includestringusingnamespacestdclassstr{private:stat

函数返回一个对象
有以下代码
#include   <iostream>
#include   <string>
using   namespace   std;
class   str
{
private:
static   int   x;
char   buf[100];
public:
str(char   *val)
{
memset(buf,   0,   100);
memcpy(buf,   val,   strlen(val));
cout < <x < < "生成对象 " < <endl;
}
~str()
{
cout < <x < < "对象销毁 " < <endl;
x++;

}

};
int   str::x=0;
str   getstring()
{
str   mystr   =   str( "HelloWorld ");
cout < < "函数getstring中 " < <endl;
return   mystr;
}
int   main()
{
str   x   =   getstring();
cout < < "HelloWorld " < <endl;
return   0;
}
执行结果如下:
0生成对象
函数getstring中
0对象销毁
HelloWorld
1对象销毁

请问对象1是在什么时候生成得

[解决办法]
如果有返回值优化的话在
str mystr = str( "HelloWorld ");这个时候
你的这个类缺少拷贝构造函数
[解决办法]
在函数返回值的时候生成了临时对象

调用的拷贝构造函数

你自己定义一个拷贝构造函数输出一串信息就知道了

热点排行