红框处,返回的temp是局部变量,当函数MyInteger& operator++(int)执行完成后,temp应该会被销毁,无法用引用类型返回。为什么这里却可以运行?(编译器是VS2022)
#include<iostream>
using namespace std;
class MyInteger
{
friend ostream& operator<<(ostream& cout, MyInteger myInt);
int m_num;
public:
MyInteger()
{
m_num = 0;
}
MyInteger(int num)
{
m_num = num;
}
// 前置自增运算符重载
MyInteger& operator++()
{
++m_num;
return *this;
}
// 前置自减运算符重载
MyInteger& operator--();
// 后置自增运算符重载
MyInteger& operator++(int) // 此处的int为占位参数, 构成函数重载
{
MyInteger temp = *this;
m_num++;
return temp;
}
// 后置自减运算符重载
};
// 前置自减运算符重载
MyInteger& MyInteger::operator--()
{
--m_num;
return *this;
}
ostream& operator<<(ostream& cout, MyInteger myInt)
{
cout << myInt.m_num;
return cout;
}
void test01()
{
MyInteger myInt;
cout << ++myInt << endl;
cout << --myInt << endl;
}
void test02()
{
MyInteger myInt;
cout << myInt++ << endl;
cout << myInt++ << endl;
//cout << myInt-- << endl;
}
int main()
{
// test01();
test02();
system("pause");
return 0;
}