C++ 声明并实现一个复数类

本文详细介绍了如何使用C++实现复数类,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载、取地址运算符重载等关键功能。
<pre name="code" class="cpp">/******************************************************************************************
complex.hpp:
	Copyright (c) Bit Software, Inc.(2013), All rights reserved.

Purpose:
	声明并实现一个复数类

难度:**

Author:
	xxx

Created Time:
	2015-4-26
******************************************************************************************/

#ifndef COMPLEX_HPP_INCLUDED
#define COMPLEX_HPP_INCLUDED
#include <iostream>
using namespace std;
class complex
{
public:
	// 带缺省值的构造函数
	complex (double real = 0, double image = 0)
		:_real(real)
		,_image(image)
	{
		cout<<"complex (double real = 0, double image = 0)"<<endl;
	}

	// 析构函数
	~complex()
	{
		cout<<"~complex()"<<endl;
	}

	// 拷贝构造函数
	complex (const complex& d)
        :_image(d._image)
		,_real(d._real)
	{
		cout<<"complex (const complex& d)"<<endl;
	}

	// 赋值运算符重载
	// 思考为什么operator=赋值函数需要一个date&的返回值??
	complex& operator= (const complex& d)
	{
		cout<<"operator= (const complex& d)"<<endl;

		if (this != &d)
		{
			this->_real = d._real;
			this->_image = d._image;
		}
		return *this;
	}

	// 取地址运算符重载
	complex* operator& ()
	{
		cout<<"operator&()"<<endl;
		return this;
	}

	// const修饰的取地址运算符重载
	const complex* operator& () const
	{
		cout<<"operator&() const"<<endl;
		return this;
	}

	void display()
	{
		cout<<"real:"<<_real<<"--image:"<<_image<<endl<<endl;
	}
	complex operator+(const complex& c)
	{
        cout<<"operator+(const complex& c)"<<endl;
        return complex(_real+c._real,_image+c._image);
	}

	complex operator-(const complex& c)
	{
        cout<<"operator-(const complex& c)"<<endl;
        return complex(_real-c._real,_image-c._image);
	}
	complex operator*(const complex& c)
	{
        cout<<"operator*(const complex& c)"<<endl;
        return complex(_real*c._real-_image*c._image,c._image*_real+_image*c._real);
	}
	complex operator/(const complex& c)
	{
        cout<<"operator/(const complex& c)"<<endl;
        return complex<span style="font-family: Arial, Helvetica, sans-serif;">((_real/c._real+_image*c._image)/(c,_real*c._real+c._image*c._image),(_image*c._real-_real*c._image)/(c,_real*c._real+c._image*c._image))</span><span style="font-family: Arial, Helvetica, sans-serif;">; </span>
	}

private:
	double _real;
	double _image;
};

#endif // COMPLEX_HPP_INCLUDED


主函数:

#include "complex.hpp"
int main()
{
    //test_complex1();
    cout << "**********************" << endl;
    complex a(1.1,2.2);
    complex b(3.3,4.4);
    complex c;
    c = a + b;
    c.display();

    c = a - b;
    c.display();

    c = a * b;
    c.display();

    c = a / b;
    c.display();


    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值