Complex.h
- /*
- + 号运算符重载
- 1.成员函数方式(单目运算符)
- 格式: 返回值类型 operator 符号(参数){}
- 2.友元函数格式 (双目运算符)
- 格式: friend 返回值类型 operator 符号(参数){}
- 注意:当两者同时存在时,在Vs2010中优先调用 成员函数重载方式
- 1. = () [] -> 只能重载为成员函数方式重载
- 2.类型转换运算符只能以成员函数方式重载
- 3.流运算符只能以友元函数方式重载
- */
- #ifndef _COMPLEX_H_
- #define _COMPLEX_H_
- class Complex{
- private:
- int real_;
- int imag_;
- public :
- Complex();
- ~Complex();
- Complex(int x , int y);
- Complex& add(const Complex& c1);
- //运算符重载声明
- //成员函数重载方式
- Complex& operator+(const Complex& c1);
- //友元函数重载方式
- friend Complex& operator+(const Complex& c1,const Complex& c2);
- void display();
- };
- #endif//_COMPLEX_H_
Complex.cpp
- #include<iostream>
- #include"Complex.h"
- using namespace std;
- Complex::Complex(){
- cout<<"Complex constructor"<<endl;
- }
- Complex::~Complex(){
- cout<<"Complex deconstructor"<<endl;
- }
- Complex::Complex(int real,int img){
- this->realreal_ = real;
- this->imag_ = img;
- }
- Complex& Complex::add(const Complex& c1){
- real_+=c1.real_;
- imag_+=c1.imag_;
- return *this;
- }
- Complex& Complex::operator+(const Complex& c1){
- cout<<"member funtion operator +"<<endl;
- real_+=c1.real_;
- imag_+=c1.imag_;
- return *this;
- }
- /**
- 实现以友元函数方式重载的+号运算符
- */
- Complex& operator+(const Complex& c1, const Complex& c2){
- cout<<"friend funtion operator +"<<endl;
- int img =c1.imag_+c2.imag_;
- int real = c1.real_ +c2.real_;
- return Complex(real,img);
- }
- void Complex::display(){
- cout<<"*********"<<endl;
- cout<<this->real_<<" "<<this->imag_<<endl;
- }
调用方式:
- //c1.add(c2);
- //成员函数重载调用方式
- //方式1
- c1+c2;
- //方式2:
- //c1.operator+(c2);
- c1.display();
- //友元函数重载方式调用
- Complex c3 =c1+c2;