// Operator learning
// C++ programming language
// P233
namespace user
{
namespace math
{
struct complex
{
douple re, im;
//
complex(double r, double i) : re(r), im(i){};
complex &operator+(complex &_cpx);
complex &operator*(complex &_cpx);
}
}
}
complex &user::math::complex::operator+(complex &_cpx){
complex cpx;
cpx.re = this.re + _cpx.re;
cpx.im = this.im + _cpx.im;
return cpx;
}
complex &user::math::complex::operatro*(complex &_cpx){
complex cpx;
cpx.re = this.re * _cpx.re - this.im * _cpx.im;
cpx.im = this.re * _cpx.im + this.im * _cpx.re;
return cpx;
}
// any other code ?
// find something from Internet
// sample of Operatro overloading
#include <string>
class PlMessageHeader
{
std::string m_ThreadSender;
std::string m_ThreadReceiver;
// return true if the messages are equal, false otherwise
inline bool operator == (const PlMessageHeader &b) const
{
return ( (b.m_ThreadSender == m_ThreadSender) &&
(b.ThreadReceiver == m_ThreadReceiver) );
}
// return true if the message is for name
inline bool isFor (const std::string &name) const
{
return (m_ThreadReceiver == name);
}
// return true if the message is for name
inline bool isFor (const char *name) const
{
// since name type is std::string,
// it becomes unsafe if name == NULL.
return (m_ThreadReveiver == name);
}
}
// Operators as member functions
// binary operator as member function
Vector2D Vector2D::operator+(const Vector2D &right) const {...}
// binary operator as non-member function
Vector2D operator+(const Vector2D &left, const Vector2D &right)
{
//...
Vector2D result;
result.set_x(left.x() + right.x());
result.set_y(left.y() + right.y());
return result;
}
// binary operator as member function with dual arguments
friend Vector2D operator+(const Vector2D &left, const Vector2D &right) {...}
// unary operator as member function
Vector2D Vector2D::operator-() const {...}
// unary operator as mon-member function
Vector2D operator-(const Vector2D &vec){...}
// An example using a 2D vector
friend ostream& operator<<(ostream& out, const Vector2D& vec) // output
{
out << "(" <<vec.x() << ", " << vec.y() << ")";
return out;
}
friend istream& operator>>(istream& in, Vector2D& vec)// input
{
double x, y;
in >> x >>y;
vec.set_x(x);
vec.set_y(y);
return in;
}