class mechanics

class Complex 
{	
public:	
	// The constructor allows an implicit conversion.
	// Watch out for hidden temporaries created by implicit conversions. explicit
	Complex(double real, double imaginary = 0) : _real(real), _imaginary(imaginary)			
	{
	}

	// 1. Prefer passing objects by const& instead of passing by value.
	// 2. "a=a+b" should be rewritten "a+=b". 
	//    operator+ should not modify this object's value, and it should return a temporary object containing the sum
	//    the return type for the temporary should be "const Complex" (not just "Complex") in order to prevent usage like "a+b=c".
	// 3. operator+ should not be a member function.
	//    you can write "a = b + 1.0" but not "a = 1.0 + b"
	// 4. = () [] and -> must be members, 
	//    and class-specific operators new, new[], delete, and delete[] must be static members
	void operator+ (Complex other)
	{
		_real = _real + other._real;
		_imaginary = _imaginary + other._imaginary;
	}
	
	// operator<< should not be a member function.
	// ostream& operator<< (ostream& os, const T& t)
	void operator<<(ostream os)
	{
		os << "(" << _real << "," << _imaginary << ")";
	}
	
	Complex operator++()  // Complex&
	{
		++_real;
		return *this;	
	}
	
	Complex operator++(int) // const Complex,  prevent a++++
	{
		Complex temp = *this;	
		++_real;	
		return temp;	
	}
	
private:
	double _real, _imaginary;  // real_
};


T& T::operator+= (const T& ohter)
{
	//
	return *this;
}

const T operator+ (const T& a, const T& b)
{
	T temp(a);
	temp += b;
	return temp;
}

//
class Complex 
{
public:
	
	explicit Complex( double real, double imaginary = 0 )  : real_(real), imaginary_(imaginary)
	{
	}
	
	Complex& operator+=( const Complex& other )
	{
		real_ += other.real_;
		imaginary_ += other.imaginary_;
		return *this;
	}
	
	Complex& operator++()
	{
		++real_;
		return *this;
	}
	
	const Complex operator++( int )
	{
		Complex temp( *this );
		++*this;
		return temp;
	}
	
	ostream& Print( ostream& os ) const
	{
		return os << "(" << real_ << "," << imaginary_ << ")";
	}
	
private:
    double real_, imaginary_;
};

const Complex operator+( const Complex& lhs, const Complex& rhs )
{
    Complex ret( lhs );
    ret += rhs;
    return ret;
}

ostream& operator<<( ostream& os, const Complex& c )
{
    return c.Print(os);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值