C++的递增重载中的运算符重载为什么不能传入后置递增的对象引用
原因为:前置递增返回的是对象本身,而后置递增返回的是temp的值
具体看代码解释
#includeusing namespace std; class integer { public: friend ostream& operator<<(ostream& cout, integer p); integer() { m_num = 10; } //如果不传回去引用就是克隆体去进行链式反应 //不能返回一个局部变量的引用 integer operator--(int) {//后置 integer temp = *this; m_num--; return temp; } private: int m_num; }; ostream& operator<<(ostream &cout,integer p)//为什么不用引用呢 {//因为后置递增函数返回的是temp cout << p.m_num; //引用的本质是一旦指向 指向不能更改 return cout; //前置递增返回的是本身(可以用引用) 而后置递增返回的不是本身(是temp即返回的是值) } //void test01() //{ // integer p; // cout << "--p="<<--p << endl; // cout << "p=" << p << endl; //} void test02() { integer p; cout << "p--=" << p-- << endl; cout <<"p=" << p << endl; } int main() { test02(); system("pause"); return 0; }



