• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Merida
博客园    首页    新随笔    联系   管理    订阅  订阅

复数的定义与运算

// complex.h

#ifndef COMPLEX_H

#define COMPLEX_H

class Complex{

private:  

      double realPart, imaginaryPart;

public:  

      Complex(double real, double imaginary);  

      void addition(const Complex &a);  

      void subtraction(const Complex &s);  

      void printComplex();  

      void setComplexNumber(double real, double imaginary);

};

#endif

 

// complexm.cpp

// member function definitions for class Complex

#include <iostream>

#include "complex.h"

using std::cout;

using std::endl;

Complex::Complex(double real, double imaginary)

{  

setComplexNumber(real, imaginary);

}

 // add complex numbers

void Complex::addition(const Complex &a)

{  

/* Write statement to add the realPart of a to the class  realPart */

     realPart += a.realPart;  

/* Write statement to add the imaginaryPart of a to the  class imaginaryPart */

     imaginaryPart += a.imaginaryPart;

} // end function addition

// subtract complex numbers

void Complex::subtraction(const Complex &s)

{

 /* Write a statement to subtract the realPart of s from the  class realPart */  

    realPart -= s.realPart;  

/* Write a statement to subtract the imaginaryPart of s from  the class imaginaryPart */

    imaginaryPart -= s.imaginaryPart;

} // end function subtraction

// print complex numbers

void Complex::printComplex()

{

 cout << '(' << realPart << ", " << imaginaryPart << ')';

} // end function printComplex

// set complex number

void Complex::setComplexNumber(double real, double imaginary)

{

     realPart = real;

     imaginaryPart = imaginary;

} // end function setComplexNumber

 

// complexTest.cpp

#include <iostream>

#include"complex.h"

using std::cout;

using std::endl;

int main()

{  

Complex b(1, 7), c(9, 2);  

b.printComplex();  

cout << " + ";  

c.printComplex();  

cout << " = ";  

b.addition(c);  

b.printComplex();

 cout << '\n';  

b.setComplexNumber(10, 1);

 c.setComplexNumber(11, 5);

 b.printComplex();  

cout << " - ";  

c.printComplex();  

cout << " = ";  

b.subtraction(c);  

b.printComplex();  

cout << endl;

 return 0;

} // end main

 

posted @ 2015-05-04 20:41  Merida  阅读(200)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3