红框处,返回的temp是局部变量,当函数MyInteger& operator++(int)执行完成后,temp应该会被销毁,无法用引用类型返回。为什么这里却可以运行?(编译器是VS2022)
#include
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;
}
在C++语言中,可以将一个自动变量转换为引用类型,即将一个局部变量的引用返回。这也就是为什么在函数myinteger& operator++(int)中,可以将temp作为引用类型返回的原因。此处应当注意的是,在该函数返回时,temp变量仍然存在,能够正常使用,但当函数结束时,temp变量会立刻被销毁,此时再使用temp变量可能会发生未定义的错误。