成员函数与友元函数的运算符重载
运算符重载允许把标准运算符(如+、—、*、/、<、>等)应用于自定义数据类型的对象
成员函数原型的格式:
函数类型 operator 运算符(参数表);
成员函数定义的格式:
函数类型 类名::operator 运算符(参数表){
函数体;
}
友元函数原型的格式:
friend 函数类型 operator 运算符(参数表);
友元函数定义的格式:
friend 函数类型 类名::operator 运算符(参数表){
函数体;
}
//Complex.h
#pragma once
#ifndef _COMPLEX_H_
#define _COMPLEX_H_
class Complex
{
public:
Complex(int real,int imag);
Complex();
~Complex();
Complex& Add(const Complex& other);
void Display() const;
Complex operator+(const Complex& other);//第一个参数为自身对象
friend Complex operator+(const Complex& c1, const Complex& c2);//友元函数不是类的成员,没有隐含自身对象,需要两个参数
private:
int real_;
int imag_;
};
#endif
//Complex.cpp
#include "Complex.h"
#include <iostream>
using namespace std;
Complex::Complex(int real, int imag) : real_(real), imag_(imag)
{
}
Complex::~Complex()
{
}
Complex& Complex::Add(const Complex &other)
{
real_ += other.real_;
imag_ += other.imag_;
return *this;
}
Complex Complex::operator+(const Complex& other)
{
int r = real_ + other.real_;
int i = imag_ + other.imag_;
return Complex(r, i);
}
Complex operator+(const Complex& c1, const Complex& c2)
{
int r = c1.real_ + c2.real_;
int i = c1.imag_ + c2.imag_;
return Complex(r, i);
}
void Complex::Display() const
{
cout << real_ << "+" << imag_ << "i" << endl;
}
//main.cpp
#include "Complex.h"
int main(void)
{
Complex c1(3,5);
Complex c2(4,6);
//c1.Add(c2);
//c1.Display();
Complex c3 = c1 + c2;//等价于 Complex c3 = c1.operator +(c2);
c1.Display();
c2.Display();
c3.Display();
return 0;
}