C++的重载
一、运算符重载
作用:赋予运算符具有操作自定义类型功能
实质:调用函数的过程
函数返回值 函数名(参数){函数体} 函数名:operator加上运算符
重载运算符有两种形式:
1.1 友元形式重载运算符(函数参数 = 操作数)
ex:两个类成员相加,则需要重载+号
class score
{
public:
score(){}
score(int math, int english) :math(math), english(english) {}
int &getMath() { return math; }
int &getEnglish() { return english; }
//法二:
friend score operator-(score score1, score score2)
{
score s0;
s0.math= score1.math - score2.math;
s0.english = score1.english - score2.english;
return s0;
}
protected:
int math;
int english;
};
//法一:
score operator+(score score1, score score2)
{
score s3;
s3.getMath() = score1.getMath() + score2.getMath();
s3.getEnglish() = score1.getEnglish() + score2.getEnglish();
return s3;
}
int main()
{
score score1(50, 40);
score score2(40, 50);
score score3 = score1 + score2; //为了是两个score类可以相加,引入了运算符重载
score score4 = score1 - score2; //翻译成score operator(score1,score2)
cout << score3.getMath() << " " << score3.getEnglish() << endl;
cout << score4.getMath() << " " << score4.getEnglish() << endl;
return 0;
}
1.2 类的函数重载运算符(函数参数 = 操作数 - 1)
class A
{
public:
A(int a,int b):a(a),b(b)
{}
A operator-(A Object) //类的函数重载运算符
{
return A(this->a - Object.a, this->b - Object.b);
}
void print()
{
cout << a << " " << b << endl;
}
protected:
int a;
int b;
};
int main()
{
A aa(10, 20);
A bb(11, 22);
A cc = aa - bb;//翻译成aa.operate-(bb)
cc.print();
return 0;
}
注意:特殊情况:
当自定义类型遇到友元类型:
class A
{
public:
A(int a):a(a)
{}
A operator-(A Object)
{
return A(this->a - Object.a);
}
void print()
{
cout << a << endl;
}
protected:
int a;
};
int main()
{
A aa(10);
A bb(11);
A cc = aa - bb;
cc = aa - 1;//此时将1转换成Object类型 翻译成aa.operator-(1);
//cc = 1 - aa; 错误,此时1不能转换成功,因为不存在1.operator-(aa);
cc.print();
return 0;
}
1.3 重载规则和限制

二、流重载
输入(>>),输出(<<)运算符重载
流对象: cin(输入流对象),cout(输出流对象)
cin: istream cout:ostream
注意:流重载只能用友元形式来重载
class A
{
public:
A(int a):a(a){}
friend istream& operator>>(istream& in, A& a)
//注意:此处A& a必须加引用,不加引用值不会改变
{
cout << "请输入a :" << endl;
in >> a.a;
return in;
}
friend ostream& operator<<(ostream& out, A a)
//此处A a不需要加引用,因为只需要使用a,不需要改变a
{
cout << a.a;
return cout;
}
protected:
int a;
};
int main()
{
A a(10);
cin >>a;
cout << a;
return 0;
}
版权声明:本文为papyyaya原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。