34.前置加加和后置加加(错误)
1.前置和后置(++/--)运算符重载
重载的++和--运算符有点让人不知所措,因为我们总是希望能根据它们出现在所作用对象的前面还是后面来调用不同的函数。解决办法很简单,例如当编译器看到++a(前置++),它就调用operator++(a),当编译器看到a++(后置++),它就会去调用operator++(int).
class Complex{
friend ostream& operator<<(ostream& os,Complex& complex){
os << "A:" << complex.mA << " B:" << complex.mB << endl;
return os;
}
public:
Complex(){
mA = 0;
mB = 0;
}
//重载前置++
Complex& operator++(){
mA++;
mB++;
return *this;
}
//重载后置++
Complex operator++(int){
Complex temp;
temp.mA = this->mA;
temp.mB = this->mB;
mA++;
mB++;
return temp;
}
//前置--
Complex& operator--(){
mA--;
mB--;
return *this;
}
//后置--
Complex operator--(int){
Complex temp;
temp.mA = mA;
temp.mB = mB;
mA--;
mB--;
return temp;
}
void ShowComplex(){
cout << "A:" << mA << " B:" << mB << endl;
}
private:
int mA;
int mB;
};
void test(){
Complex complex;
complex++;
cout << complex;
++complex;
cout << complex;
Complex ret = complex++;
cout << ret;
cout << complex;
cout << "------" << endl;
ret--;
--ret;
cout << "ret:" << ret;
complex--;
--complex;
cout << "complex:" << complex;
}
2.视频内容
程序1:
#pragma warning(disable:4996)
//2022年10月12日22:09:19
#include <iostream>
using namespace std;
void test01()
{
int a = 1;
cout << ++a << endl;
cout << a++ << endl;
cout << a << endl;
++(++a);
}
class Maker
{
friend ostream &operator<<(ostream &out, Maker &m);
public:
Maker(int a)
{
this->a = a;
}
//重载前置加加
//Maker &operator++()
//{
// this->a = a;
//}
//后置加加
//Maker &operator++()
//{
// ++this->a;
// return *this;
//}
private:
int a;
};
ostream &operator<<(ostream &out, Maker &m)
{
out << m.a << endl;
return out;
}
void test02()
{
Maker m1(1);
cout << m1 << endl;
//cout << ++m1 << endl;
//++(++m1);
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}
输出结果:
1
请按任意键继续. . .
程序2:
55行出现错误
错误 C2679 二元“<<”: 没有找到接受“Maker”类型的右操作数的运算符(或没有可接受的转换) 10前置加加和后置加加
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
void test()
{
int a = 1;
cout << ++a << endl;
cout << a++ << endl;
cout << a << endl;
++(++a);
}
class Maker
{
friend ostream &operator<<(ostream &out, Maker &m);
public:
Maker(int a)
{
this->a = a;
}
//重载前置加加
Maker &operator++()
{
++this->a;
return *this;
}
//后置加加,
Maker operator++(int)//占位参数,必须是int
{
//后置加加,先返回,后加加
Maker tmp(*this);//1.*this里面的值a是等于2
++this->a;//这个对象的a等3
return tmp;
}
private:
int a;
};
ostream &operator<<(ostream &out, Maker &m)
{
out << m.a << endl;
return out;
}
void test02()
{
Maker m1(1);
cout << m1 << endl;//1
cout << ++m1 << endl;//2
//++(++m1);
cout << m1++ << endl;//2 这里返回的拷贝的tmp对象
cout << m1 << endl;//3 这里返回的是++this->a的对象
//同等条件下,优先使用前置加加,不需要产生新的对象和调用拷贝构造
}
int main()
{
test02();
system("pause");
return EXIT_SUCCESS;
}