运算符重载
作用:用于自定义运算
形式:如:
1 类名 operator+( 类名 形参名, 类名 形参名 ){}
2 类名 operator+( 类名 形参名 ){}
代码实现1
#include<iostream>
using namespace std;
class complex{
friend complex operator+( const complex &A, const complex &B );
private:
int real, imag;
public:
complex( const int &r = 0, const int &i = 0 ):real(r), imag(i){};
void getComplex(){
cout << real << "+" << imag << "i" << endl;
}
};
complex operator+( const complex &A, const complex &B ){
complex C;
C.real = A.real + B.real;
C.imag = A.imag + B.imag;
return C;
}
int main(){
complex c1( 1, 1 ), c2( 2, 2 ), c3;
c3 = c1 + c2;
c3.getComplex();
return 0;
}
运行结果1
代码实现2
#include<iostream>
using namespace std;
class complex{
private:
int real, imag;
public:
complex( const int &r = 0, const int &i = 0 ):real(r), imag(i){};
void getComplex(){
cout << real << "+" << imag << "i" << endl;
}
complex operator+( const complex &A ){
complex B;
B.real = this->real + A.real;
B.imag = this->imag + A.imag;
return B;
}
};
int main(){
complex c1( 1, 1 ), c2( 1, 1 ), c3;
c3 = c1 + c2;
c3.getComplex();
return 0;
}
运行结果
总结
重载实际就是自己定义一个现有的函数,+运算符不可以对自定义类进行加法运算,否则将会出现错误,故我们自己定义一个函数使其相加变得合理;
重载的另一层含义则是输入的参数不同即为重载;
同理,-*/都可进行重载;