函数返回局部变量的引用或指针
不是说函数不可以返回指向局部变量或临时变量的引用吗? 那么下面我这个代码为什么执行结果是对的,没有发现问题?//---file1:mytime.h Time类的声明
#ifndef MY_TIME_H_
#define MY_TIME_H_
class Time
{
public:
Time();
Time(int h, int m=0);
void AddMin(int m);
void AddHour(int h);
void Reset(int h=0, int m=0);
const Time &Sum(const Time &t) const;
void Show() const;
private:
int hours;
int minutes;
};
#endif
//file2:mytime.cpp 类的实现
#include <iostream>
#include "mytime.h"
Time::Time()
{
hours=minutes=0;
}
Time::Time(int h,int m)
{
hours=h;
minutes=m;
}
void Time::AddHour(int h)
{
hours+=h;
}
void Time::AddMin(int m)
{
minutes+=m;
hours+=minutes/60;
minutes%=60;
}
void Time::Reset(int h, int m)
{
hours=h;
minutes=m;
}
const Time &Time::Sum(const Time &t) const // 这里的sum是局部变量,函数执行完毕,变量被销毁.我这里
{
Time sum; //返回指向局部变量sum的引用,为什么编译没有出错啊?
sum.minutes=minutes+t.minutes;
sum.hours=hours+t.hours+sum.minutes/60;
sum.minutes %= 60;
return sum;
}
void Time::Show() const
{
std::cout << hours << "hours" << minutes << "minutes";
}
//file3:usetime.cpp
#include <iostream>
#include "mytime.h"
int main()
{
using std::cout;
using std::endl;
Time planning;
Time coding(2,40);
Time fixing(5,55);
Time total;
cout << "planning time =";
planning.Show();
cout << endl;
cout << "coding time=";
coding.Show();
cout << endl;
cout << "fixing time=";
fixing.Show();
cout << endl;
total=coding.Sum(fixing);
cout << "coding.sum(fixing)=";
total.Show();
cout << endl;
return 0;
}
执行结果是对了.
哪位能指教一下,感激不尽!