返回信息流class complex
{
double realpart;
double imagepart;
public:
complex(){}
~complex(){}
complex operator + (complex& ,complex& );
}
complex complex::operator +(complex&com1 ,complex&com2 )
{
complex temp;
temp.realpart=com1.realpart+com2.realpart;
temp.imagepart=com1.imagepart+com2.imagepart;
return temp; // 为什么这个临时对象能返回?不是在返回时被析构了吗?
}
这是一条镜像帖。来源:北邮人论坛 / soft-design / #16696同步于 2007/4/14
该镜像源已超过 30 天没有更新,可能在源站已被删除。
SoftDesign机器人发帖
问一个C++中运算符重载的问题
commonplace
2007/4/14镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
俺来回答以下这个问题。
首先声明一下,这个问题和操作符重载没有直接联系。只要是函数就有这样的性质。
我贴一段代码,用代码来说明问题。
#include<iostream>
#include<time.h>
#include<vector>
#include<list>
using namespace std;
class Event
{
public:
//time_t time;
Event(int e):num(e){cout << num <<" construced!"<<endl;}
int num;
// Message msg
Event(const Event& h):num(h.num){cout << num <<" copy constructor is used! !"<<endl;}
~Event(){cout << num << " destructed\n"; }
void print()
{ cout<<"num"<<num<<endl;}
};
Event func(int i)
{
return Event(i);
}
Event func2(int i)
{
Event temp(i);
return temp;
}
int main()
{
func(8);
func2(4);
return 0;
}
这段代码的运行结果是:
8 construced!
8 destructed
4 construced!
4 copy constructor is used! !
4 destructed
4 destructed
Press any key to continue
这样的意思表明。
1.如果在函数体中定义了一个临时变量,并且这个变量是要被返回的。那么在返回前就会先用拷贝构造函数构造一个新的变量(temporary object),并且将这个临时对象返回。也就是说返回的不是那个temp。
2.有一种减少开销的方法,就是直接在return的时候构造一个对象。就像func()中做的那样。可以从结果中看到,这样的话只会构造一次对象。当然这样的话你就不能在函数中使用这个对象了。
用哪种就看你需要了。呵呵。