来源:http://www.cnblogs.com/jiaohuang/
c++中要对操作符进行重载(除了 ☆ . ☆ .* ☆ :: ☆ ? : ☆ sizeof ☆ typeid 这几个运算符不能被重载,其他运算符都能被重载)
1在类中重载+=操作符
赋值操作符必须定义为成员函数,无论形参为何种类型
赋值必须返回*this 的引用
class Love{
public:
int str;
int agi;
int intel;
Love(): str(0), agi(0) , intel(0){}
Love(int a , int b ,int c): str(a), agi(b) , intel(c){};
Love& operator+=(const Love &test){
str += test.str;
agi += test.agi;
intel += test.intel;
return *this;
}
};
int main(){
Love boy ,girl(10,20,30);
boy += girl;
cout << boy.str << boy.agi << boy.intel << endl;
return 0;
}
在类外面重载+号
class Love{
public:
int str;
int agi;
int intel;
Love(): str(0), agi(0) , intel(0){}
Love(int a , int b ,int c): str(a), agi(b) , intel(c){};
};
//为了与内置操作符保持一致,加法返回一个右值,而不是引用
Love operator+(const Love &fir, const Love &sec){
Love ans;
ans.str = fir.str + sec.str ;
ans.agi = fir.agi + sec.agi ;
ans.intel = fir.intel + sec.intel;
return ans;
}
在类外面的输入输出操作符
为什么IO操作符必须为非成员函数?
因为做操作数只能是该类类型的对象
比如 Love item;
item << cout ;
由于IO操作符通常对非公用数据成员进行读写,所以通常将IO操作符
设定为友元
C++中对于<<,>>的重载学习
#include<iostream>
using namespace std;
class PhoneNumber;
ostream &operator<<(ostream &,const PhoneNumber &);
istream &operator>>(istream &,PhoneNumber &);
class PhoneNumber
{
public://对于friend来着public可有可无
friend ostream &operator<<(ostream &,const PhoneNumber &);
friend istream &operator>>(istream &,PhoneNumber &);
private:
char areacode[10];
char exchange[10];
char line[10];
};
ostream &operator<<(ostream &output, const PhoneNumber &num)//就是格式化输出
{
output<<"("<<num.areacode<<")";
output<<"-----"<<num.line;
return output;
}
istream &operator>>(istream &input,PhoneNumber &num)//格式化输入
{
input.ignore();
input.getline(num.areacode,10);
input.ignore(2);//从第一位开始向后忽略几个字符
// input.ignore();
input.getline(num.line,10);
return input;
}
int main()
{
PhoneNumber phone;
cout<<"输入一个电话号码:"<<endl;
cin>>phone;
cout<<"输入的电话号码是:"<<phone<<endl;
return 0;
}