【www.bbyears.com--js教程】
加法运算重载
调用对象自身成员变量发送改变 标签: <无>
代码片段
#pragma once
class Complex
{
public:
Complex(void);
~Complex(void);
Complex(int real,int imag);
int get_real()const;
int get_imag()const;
void Display()const;
void Addone(const Complex& other);
Complex operator+(const Complex& other);
private:
int real_;
int imag_;
};
Complex::Complex(void) {}
Complex:: Complex(int real,int imag):real_(real),imag_(imag) {}
int Complex:: get_real()const
{ return real_;
}
int Complex:: get_imag ()const
{ return imag_;
}
void Complex::Display()const
{ cout<
void Complex::Addone(const Complex& other)
{ real_+=other.get_real();
imag_+=other.get_imag();
}
Complex Complex::operator+(const Complex& other)//调用对象自身的值发生了改变
{ real_+=other.get_real();
imag_+=other.get_imag();
return *this;
}
Complex::~Complex(void)
{
}
#include<iostream>
#include "Complex.h"
using namespace std;
Complex Add( Complex& A, Complex& B)
{ return Complex(A.get_real()+B.get_real(),A.get_imag()+B.get_imag());
};
void main()
{ Complex a(10,5);
Complex b(11,0);
Complex c;
a.Display();
b.Display();
c = Add(a,b);
c.Display();
c.Addone(a);
c.Display();
a+b; //与a的类成员函数调用a.operator+(b)等价
a.Display();
}
运算符重载返回新的对象
代码片段
#pragma once
class Complex
{
public:
Complex(void);
~Complex(void);
Complex(int real,int imag);
int get_real()const;
int get_imag()const;
void Display()const;
void Addone(const Complex& other);
Complex operator+(const Complex& other);
private:
int real_;
int imag_;
};
#include "Complex.h"
#include<iostream>
using namespace std;
Complex::Complex(void) {}
Complex:: Complex(int real,int imag):real_(real),imag_(imag) {}
int Complex:: get_real()const
{ return real_;
}
int Complex:: get_imag ()const
{ return imag_;
}
void Complex::Display()const
{ cout<
void Complex::Addone(const Complex& other)
{ real_+=other.get_real();
imag_+=other.get_imag();
}
//Complex Complex::operator+(const Complex& other)//调用对象自身的值发生了改变
//{ real_+=other.get_real();
// imag_+=other.get_imag();
// return *this;
//}
Complex Complex::operator+(const Complex& other)//调用对象自身不发生改变
{ int i,j;
i=real_+other.get_real();
j=imag_+other.get_imag();
return Complex (i,j);
}
Complex::~Complex(void)
{
}
#include
#include "Complex.h"
using namespace std;
Complex Add( Complex& A, Complex& B)
{ return Complex(A.get_real()+B.get_real(),A.get_imag()+B.get_imag());
};
void main()
{ Complex a(10,5);
Complex b(11,0);
Complex c;
a.Display();
b.Display();
c = Add(a,b);
c.Display();
c.Addone(a);
c.Display();
c=a+b; //与a的类成员函数调用a.operator+(b)等价
c.Display();
}