标签:
写一个复数类,实现基本的运算,目的熟悉封装与数据抽象。
#include <iostream> #include <vector> using namespace std; class Complex{ friend ostream & operator << (ostream & os, const Complex &); //重载输出标识符 friend Complex operator + (const Complex&, const Complex &); friend Complex operator - (const Complex&, const Complex &); friend Complex operator * (const Complex&, const Complex &); friend Complex operator % (const Complex&, const Complex &); public: Complex() = default; Complex(int a, int b) : first(a), second(b) {}; //构造函数 Complex(const Complex&); //拷贝构造函数;参数必须是const型的 Complex & operator = (const Complex &); //拷贝赋值运算符 Complex & operator += (const Complex &); Complex & operator -= (const Complex &); Complex & operator *= (const Complex &); Complex & operator %= (const Complex &); ~Complex(){}; //析构函数 private: int first = 0; int second = 0; };
#include "complex.h" using namespace std; ostream & operator << (ostream &os, const Complex &item) { if (item.second > 0) os << item.first << " + " << item.second << "i"; else if (item.second < 0) os << item.first << " - " << -item.second << "i"; else os << item.first; return os; } Complex::Complex(const Complex& rhs) { this->first = rhs.first; this->second = rhs.second; } Complex &Complex::operator= (const Complex &rhs) { this->first = rhs.first; this->second = rhs.second; return *this; } // 重载运算符 += 和 + :各自实现 Complex & Complex::operator += (const Complex & rhs) //类内的重载运算符,参数只能有一个 { this->first += rhs.first; this->second += rhs.second; return *this; } Complex operator + (const Complex &lhs, const Complex &rhs) { Complex tmp; tmp.first = lhs.first + rhs.first; tmp.second = lhs.second + rhs.second; return tmp; } // 重载运算符- 和-= : -= 用 - 来实现 Complex operator - (const Complex &lhs, const Complex &rhs) { Complex tmp; tmp.first = lhs.first - rhs.first; tmp.second = lhs.second - rhs.second; return tmp; } Complex & Complex::operator-= (const Complex &rhs) { *this = *this - rhs; return *this; } // 重载运算符 *= 和 * :* 用 *= 来实现 Complex & Complex::operator *= (const Complex &rhs) { int tmpFirst = first * rhs.first; if (second * rhs.second > 0) tmpFirst -= second * rhs.second; else tmpFirst += second * rhs.second; second = first * rhs.second + second * rhs.first; first = tmpFirst; return *this; } Complex operator * (const Complex &lhs, const Complex &rhs) { Complex tmp=
lhs; tmp *= rhs; return tmp; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4927605.html