运算符重载
成员函数单目
#include<iostream>
using namespace std;
class A{
int p;
public:
A (int a){
p = a;
}
A operator++(){
p++;
return *this;
}
A operator++(int){
A temp(*this);
p++;
return temp;
}
void show(){
cout<<p<<endl;
}
};
int main(int argc, char const *argv[])
{
A a(10);
++a;
a++;
a.show();
return 0;
}
成员函数双目
#include<cstring>
#include<iostream>
using namespace std;
class A{
int p;
public:
A (int a){
p = a;
}
A operator +(A& a);/*这里的&一定要用*/
void show(){
cout<<p<<endl;
}
};
A A:: operator +(A& a){/*不用友元时,相当于用了一波this,强调一下他直接第一个调用*this*/
A temp(0);/*这里不能用 A temp*/
temp.p = p + a.p;
return temp;
}
int main(int argc, char const *argv[])
{
A a(10),b(5);
A c = a + b;
c.show();
return 0;
}
友元函数单目
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
class A{
int p;
public:
A(int a){
p = a;
};
friend A operator ++(A &a){
a.p++;
return a;
}
friend A operator++(A &a,int){
A temp = a;
a.p++;
return temp;
}
void show(){
cout<<p<<endl;
}
};
int main(int argc, char const *argv[])
{
A a(10);
a++;
a.show();
return 0;
}
友元函数双目
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
class A{
int p;
public:
A(int a){
p = a;
};
friend A operator +(A &a,A &b){
A c(0);
c.p = a.p + b.p;
return c;
}
void show(){
cout<<p<<endl;
}
};
int main(int argc, char const *argv[])
{
A a(10),b(10);
A c = a + b;
c.show();
return 0;
}