C++递增运算符重载遇到的引用问题
近日学习黑马程序员的第123个C++视频 递增运算符重载 时遇到了一些问题,特此记录
左移运算符重载
在黑马的前一节视频,左移运算符重载时,代码如下
ostream& operator<<(ostream &cout,Person &p)//这里的p是用引用的方式传递的
{
cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
return cout;
}
递增运算符重载
在学习递增运算符时,当我尝试直接复制上一节使用的左移运算符重载代码时,发生了错误,如下图所示(完整的代码在最后面)
错误聚焦在了第47行,编译器不认识cout<<myint++。
经过仔细对比发现左移运算符重载是用引用的方式传入myInt类,但后置递增运算符返回的是值传递,两者不匹配所以发生报错。
小结
返回的局部变量,不能以引用的形式作为另一个函数的传入参数。另外自己编程的时候也要注意当返回值是局部变量时,函数使用完,局部变量就销毁了,不能二次使用。我理解的还有不到位的地方,欢迎各位大佬指正。
改正前的源代码
#include <iostream>
using namespace std;
class myInt
{
friend ostream& operator<<(ostream &cout, myInt& myint);
public:
myInt()
{
m_int = 0;
}
//前置运算符
myInt& operator++()
{
m_int++;
return *this;
}
//后置运算符
myInt operator++(int)
{
myInt temp = *this;
m_int++;
return temp;
}
private:
int m_int;
};
//重载<<运算符
ostream& operator<<(ostream& cout, myInt& myint)
{
cout << "m_int = " << myint.m_int << endl;
return cout;
}
void test01()
{
myInt myint;
cout << myint++ << endl;
cout << ++myint << endl;
}
int main()
{
test01();
}
改正后的源代码
#include <iostream>
using namespace std;
class myInt
{
friend ostream& operator<<(ostream &cout, myInt myint);
public:
myInt()
{
m_int = 0;
}
//前置运算符
myInt& operator++()
{
m_int++;
return *this;
}
//后置运算符
myInt operator++(int)
{
myInt temp = *this;
m_int++;
return temp;
}
private:
int m_int;
};
//重载<<运算符
ostream& operator<<(ostream& cout, myInt myint)
{
cout << "m_int = " << myint.m_int << endl;
return cout;
}
void test01()
{
myInt myint;
cout << myint++ << endl;
cout << ++myint << endl;
}
int main()
{
test01();
}