复数类(C++习题一)
复数类(C++练习一)
写一个复数类,实现基本的运算,目的熟悉封装与数据抽象。
- 类的定义
#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; }
- %和%=没有实现,和前面的应该都一样
- 在同时定义了算术运算符和相关的复合赋值运算符时,通常情况下用复合赋值来实现算术运算符
- 对于类外的重载运算符,返回的不是引用,在函数内定义的临时变量在离开时不会被系统收回,如果返回引用则会指向未开辟的区域
- 对于类内的重载运算符,会默认把第一个参数绑定到this上,所以形参永远少一个,所以对于二目的运算符,只能有一个参数
- friend只是告诉类友元,并没有声明;最好在头文件中再次单独声明一次来满足可移植性
- 在visul stdio中可以直接在其他文件中定义,自动会找到
- 如果在clang编译器中需要在头文件中声明一次,包含进去
- 注意在友元函数声明时,如果要写在类前面,必须保证类已经声明过