友元
运算符重载
+运算符重载
<<运算符重载
++运算符重载
注意!!!
代码
#include<iostream>
using namespace std;
class person{
public:
int name1;
int name2;
// person operator+ (person &p1){
// person tem(0,0);
// tem.name1 = name1+p1.name1;
// tem.name2 = name2+p1.name2;
// return tem;
// };
person(int a,int b):name1(a),name2(b)
{
};
};
class myint{
friend ostream& operator<<(ostream &cout,myint out);
public:
myint(){
this->num = 0;
}
// 前置++ 返回引用是为了一直对一个数据操作
myint& operator++(){
this->num ++;
return *this;
}
// 后置++ 加占位 int 区分,一定返回值
myint operator++(int ){
myint tem = *this;
this->num ++;
return tem;
}
private:
int num;
};
person operator+(person &a,person &b){
person tem(0,0);
tem.name1 = a.name1+b.name1;
tem.name2 = a.name2+b.name2;
return tem;
}
ostream& operator<<(ostream &cout,person &out){
cout << out.name1 << " " << out.name2 ;
return cout;
}
void test1(){
person p1(1,2);
person p2(1,2);
person p3=p1+p2;
std::cout<< p3.name1 <<" " << p3.name2 << endl;
cout << p3 << endl;
}
//后置递增的++ 是右值,不能加 myint&
ostream& operator<<(ostream &cout,myint out){
cout << out.num;
return cout;
}
void test2(){
myint num;
cout << ++(++num) << endl;
cout << num << endl;
}
void test3(){
myint num;
cout << num++ << endl;
cout << num << endl;
}
int main(){
test3();
test2();
}