明白了函数重载后,运算符的重载就是小意思了。
但是运算符的重载在实现起来有一定的规则。
First:双目运算符
运算符重载为成员函数形式。
格式:类名 operator运算符(const 类名 &对象名) const{}
具体的还是看代码吧。
View Code
#include "iostream"
#include "cstring"
#include "string"
#include "cstdio"
using namespace std;
class Complex{
public:
Complex(double r=0.0, double i=0.0):real(r),imag(i){}
Complex operator+(const Complex &c2) const{ //重载"+"
return Complex(real+c2.real, imag+c2.imag);
}
Complex operator-(const Complex &c2) const{ //重载"-"
return Complex(real-c2.real, imag-c2.imag);
}
void display(){
cout<<"("<<real<<","<<imag<<")"<<endl;
}
private:
double real;
double imag;
};
int main(){
Complex c1(5, 4), c2(2, 10), c3;
cout<<"c1="; c1.display();
cout<<"c2="; c2.display();
c3 = c1+c2;
cout<<"c3=c1+c2="; c3.display();
c3 = c1-c2;
cout<<"c3=c1-c2="; c3.display();
}
Second:单目运算符
运算符重载为成员函数形式。
格式:类名& operator运算符(){} 或者 类名 operator运算符(int){}
具体的还是来看代码。
View Code
#include "iostream"
#include "cstring"
#include "string"
#include "cstdio"
using namespace std;
class Clock{
public:
Clock(int hour=0, int minute=0, int second=0){
if(hour>=0 && hour<24 && minute>=0 && minute<60 && second>=0 && second<60){
this->hour = hour;
this->minute = minute;
this->second = second;
}else cout<<"Time Error!"<<endl;
}
void showTime() const{
cout<<hour<<":"<<minute<<":"<<second<<endl;
}
Clock& operator++(){ //后置++, 只要是无参的,就是后置的,注意这里有&
second++;
if(second>=60){
second -= 60;
minute++;
if(minute>=60){
minute -= 60;
hour = (hour+1)%24;
}
}
return *this;
}
Clock operator++(int){ //前置++, 只要是有参的,就是前置的,注意这里没&
Clock old = *this;
++(*this);
return old;
}
private:
int hour;
int minute;
int second;
};
int main(){
Clock myClock(23, 45, 56);
cout<<"at first: "; myClock.showTime();
cout<<"myClock++: "; (myClock++).showTime();
cout<<"++myClock: "; (++myClock).showTime();
}
上面所讲的都运算符重载为成员函数形式的重载,
下面来讲讲运算符重载为非成员函数形式的重载。
其实很简单,就只要在重载函数前面加上一个friend可以了。
但是有一点要注意:在重载为成员函数时,省去了一个参数。
那么在重载为非成员函数时,每一个参数都要传入了,不可以省。
还有一点就是要将修饰符const去掉。
好了,就这三点注意了。
再来总结一下:
1.加friend
2.每个参数都要传入,不能省
3.去掉修饰符const
下面来看一个代码吧。
View Code
#include "iostream"
#include "cstring"
#include "string"
#include "cstdio"
using namespace std;
class Complex{
public:
Complex(double r=0.0, double i=0.0):real(r),imag(i){}
friend Complex operator+(const Complex &c1, const Complex &c2) { //重载"+"
return Complex(c1.real+c2.real, c1.imag+c2.imag);
}
friend Complex operator-(const Complex &c1,const Complex &c2) { //重载"-"
return Complex(c1.real-c2.real, c1.imag-c2.imag);
}
void display(){
cout<<"("<<real<<","<<imag<<")"<<endl;
}
private:
double real;
double imag;
};
int main(){
Complex c1(5, 4), c2(2, 10), c3;
cout<<"c1="; c1.display();
cout<<"c2="; c2.display();
c3 = c1+c2;
cout<<"c3=c1+c2="; c3.display();
c3 = c1-c2;
cout<<"c3=c1-c2="; c3.display();
}
原文链接: https://www.cnblogs.com/o8le/archive/2012/04/21/2462227.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/48158
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!