#C++PrimerPlus# Chapter11_Exersice7_complex

定义一个复数类,并检验它。

Complex类

私有部分:数据成员,复数的实部与虚部;

公有部分:1,构造与析构函数;

     2,设置数据成员的函数;

     3,重载运算符函数“+”,“-”,“*”,“~”;

     4,友元函数 重载“*” "<<" ">>" 运算符。

程序清单如下:


// complex.h
#ifndef COMPLEX_H_
#define COMPLEX_H_

#include <iostream>

class Complex
{
private:
  // 数据成员
  double realPart;
  double imagPart;
public:
  // 构造与析构函数
  Complex();
  Complex(double m_real, double m_imag = 0);
  ~Complex();
  // 设置数据成员的函数
  void reset(double m_real, double m_imag = 0);
  // 重载运算符
  Complex operator+(const Complex& b) const;
  Complex operator-(const Complex& b) const;
  Complex operator*(const Complex& b) const;
  //Complex operator*(double b) const;
  Complex operator~() const;
  // 友元函数
  friend Complex operator*(double a, const Complex& b);
  friend std::ostream& operator<<(std::ostream& os, const Complex& b);
  friend bool operator>>(std::istream& in, Complex& b);
};

#endif


// complex.cpp
#include "complex.h"

// 定义类方法与友元函数
// 定义构造与析构函数
Complex::Complex()
{
  realPart = imagPart = 0.0;
}
Complex::Complex(double m_real, double m_imag)
{
  realPart = m_real;
  imagPart = m_imag;
}
Complex::~Complex()
{
}
// 定义设置数据成员的函数
void Complex::reset(double m_real, double m_imag)
{
  realPart = m_real;
  imagPart = m_imag;
}
// 定义重载运算符
Complex Complex::operator+(const Complex& b) const
{
  return Complex (realPart + b.realPart, imagPart + b.imagPart);
}
Complex Complex::operator-(const Complex& b) const
{
  return Complex (realPart - b.realPart, imagPart - b.imagPart);
}
Complex Complex::operator*(const Complex& b) const
{
  return Complex (realPart * b.realPart - imagPart * b.imagPart,
  realPart * b.imagPart + imagPart * b.realPart);
}
Complex Complex::operator~() const
{
  return Complex (realPart, -imagPart);
}
// 定义友元函数
Complex operator*(double a, const Complex& b)
{
  return b * a;
}
std::ostream& operator<<(std::ostream& os, const Complex& b)
{
  os << "(" << b.realPart << "," << b.imagPart << "i)";
  return os;
}
bool operator>>(std::istream& in, Complex& b)
{
  using std::cout;

  bool result;
  double real, imag;
  cout << "real: ";
  if (in >> real)
  {
    cout << "imaginary: ";
    if (in >> imag)
    {
      b.reset(real, imag);
      result = true;
    }
  }
  else
    result = false;
  return result;
}


// usecomplex.cpp
#include "complex.h"

int main()
{
  using std::cin;
  using std::cout;
  using std::endl;

  Complex a (3, 4);
  Complex c;
  cout << "Enter a complex number (q to quit)\n";
  while (cin >> c)
  {
    cout << "c is " << c << endl;
    cout << "complex conjugate is " << ~c << endl;
    cout << "a is " << a << endl;
    cout << "a + c is " << a + c << endl;
    cout << "a - c is " << a - c << endl;
    cout << "a * c is " << a * c << endl;
    cout << "2 * c is " << 2 * c << endl;
    cout << "Enter a complex number (q to quit)\n";
  }
  cout << "Done!";
  system("pause>nul");
  return 0;
}


结束。

posted @ 2013-05-12 22:35  庄懂  阅读(119)  评论(0编辑  收藏  举报