您的位置:首页 > 编程语言 > C语言/C++

C++程序设计(第2版)课后习题答案--第12章

2013-03-25 15:40 441 查看
View Code

// 文件complex.h: 复数类的定义
#ifndef __COMPLEX__H__
#define __COMPLEX__H__

class Complex
{
public:
Complex(double = 0.0, double = 0.0);
Complex operator + (const Complex &) const;
Complex operator - (const Complex &) const;
//Complex & operator = (const Complex &);
void print()const;

private:
double real; // 实数部分
double imaginary; // 虚数部分
};

#endif
// 文件complex.cpp: 复数类的实现
#include <iostream.h>
#include "complex.h"

Complex::Complex(double r, double i)
{
real = r;
imaginary = i;
}

void Complex::print()const
{
cout << '(' << real << ", " << imaginary << ')';
}

Complex Complex::operator + (const Complex &operand2) const
{
Complex sum;
sum.real = real + operand2.real;
sum.imaginary = imaginary + operand2.imaginary;
return sum;
}

Complex Complex::operator - (const Complex &operand2) const
{
Complex diff;
diff.real = real - operand2.real;
diff.imaginary = imaginary - operand2.imaginary;
return diff;
}

//Complex &Complex::operator = (const Complex &right)
//{
//    real = right.real;
//    imaginary = right.imaginary;
//    return  *this;
//}
// 文件ex13_1.cpp: 主函数定义,通过运算符操作复数对象
#include <iostream.h>
#include "complex.h"

int main()
{
Complex x, y(4.3, 8.2), z(3.3, 1.1);

// 输出x,y,z
cout << "x: ";
x.print();
cout << "\ny: ";
y.print();
cout << "\nz: ";
z.print();

//输出加法运算
x = y + z;
cout << "\n\nx = y + z:\n";
x.print();
cout << " = ";
y.print();
cout << " + ";
z.print();

//输出减法运算
x = y - z;
cout << "\n\nx = y - z:\n";
x.print();
cout << " = ";
y.print();
cout << " - ";
z.print();
cout << '\n';

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: