注:定义的类名为Demo ,实现方法为友元和类内函数重载两种,除左移,因为左移运算符重载只能使用友元,绿色标注为友元,红色为左移,黑色为类内函数
1.+运算符重载,用友元和类内函数实现重载
#include<iostream>
using namespace std;
#include<string>
class Demo
{
public:
Demo(int _a = 0, int _b = 0)//构造函数
{
a = _a;
b = _b;
cout << "Demo(int ,int)" << endl;
}
~Demo()//析构函数
{
cout << "~Demo()" << endl;
}
void show()
{
cout << "a" << a << endl;
cout << "b" << b << endl;
}
//friend Demo operator+(Demo &_demo1, Demo &_demo2);//1.友元,类内声明
Demo operator+(Demo &_demo2)
{
cout << "2.成员函数" << endl;
Demo temp(0, 0);
temp.a = this->a + _demo2.a;
temp.b = this->b + _demo2.b;
return temp;
}
pivate:
int a;
int b;
};
/*Demo operator+(Demo &_demo1, Demo &_demo2)
{
cout << "友元,类外定义" << endl;
Demo temp(0, 0);
temp.a = _demo1.a + _demo2.a;
temp.b = _demo2.b + _demo2.b;
return temp;
}*/
int main()
{
Demo demo1(1, 1);
Demo demo2(1, 2);
Demo demo3 = demo1 + demo2;
demo3.show();
return 0;
}
2.前置++运算符
#include<iostream>
using namespace std;
#include<string>
class Demo
{
public:
Demo(int _a = 0, int _b = 0)
{
a = _a;
b = _b;
cout << "Demo(int ,int)" << endl;// 构造函数
}
~Demo()//析构函数
{
cout << "~Demo()" << endl;
}
void show()
{
cout << "a" << a << endl;
cout << "b" << b << endl;
}
//friend Demo operator++(Demo demo1);//1.友元,类内声明
Demo &operator++()2.类内函数重载
{
++this->a;
++this->b;
return *this;
}
private:
int a;
int b;
};
/*Demo operator++(Demo demo1)//友元,类外定义
{
cout<<"友元"<<endl;
++demo1.a;
++demo1.b;
return demo1;
}*/
int main()
{
Demo demo1(1, 1);
Demo demo3= ++demo1;//调用拷贝构造,只会产生一次初始化
Demo demo4;
demo4.show();//初始化两次
demo3.show();
return 0;
}
3.后置++与左移运算符重载
#include<iostream>
using namespace std;
#include<string>
class Demo
{
public:
Demo(int _a = 0, int _b = 0)
{
a = _a;
b = _b;
cout << "Demo(int,int)"<<endl;
}
~Demo()
{
cout << "~Demo()" << endl;
}
void show()
{
cout << "a" << a<<endl;
cout << "b" << b<<endl;
}
//friend Demo operator++(Demo &demo1, int);//友元,
Demo operator++(int)
{
Demo temp = *this;
this->a++;
this->b++;
return temp;
}
friend void operator<<(ostream &_cout, Demo &demo1);
private:
int a;
int b;
};
void operator<<(ostream &_cout, Demo &demo1)//左移运算符,参数1是cout,参数二是demo
{
cout << demo1.a << "," << demo1.b << endl;
}
/*Demo operator++(Demo &demo1, int)// int 只是表示运算符为后置++
{
Demo demo=demo1;//定义一个临时变量存储传进来的值
demo1.a++;
demo1.b++;
return demo;
}*/
int main()
{
Demo demo1(2, 6);
Demo demo2 = demo1++;
demo2.show();
cout << demo1;
demo1.show();
return 0;
}