complex.h文件的函数声明如下:

class COMPLEX { public: COMPLEX(double r = 0, double i = 0); COMPLEX(const COMPLEX &other); void print(); COMPLEX operator+(const COMPLEX &other); COMPLEX operator-(const COMPLEX &other); COMPLEX operator-(); COMPLEX operator=(const COMPLEX &other); COMPLEX & operator++(); COMPLEX operator++(int); COMPLEX & operator--(); COMPLEX operator--(int); protected: double real, image; };

现在需要在complex.cpp文件中实现这些函数。以下是对应的实现:

#include "complex.h" #include

// 构造函数 COMPLEX::COMPLEX(double r, double i) { real = r; image = i; }

// 拷贝构造函数 COMPLEX::COMPLEX(const COMPLEX &other) { real = other.real; image = other.image; }

// 打印复数 void COMPLEX::print() { std::cout << real << " + " << image << "i" << std::endl; }

// 重载加法运算符(二元) COMPLEX COMPLEX::operator+(const COMPLEX &other) { COMPLEX result; result.real = real + other.real; result.image = image + other.image; return result; }

// 重载减法运算符(二元) COMPLEX COMPLEX::operator-(const COMPLEX &other) { COMPLEX result; result.real = real - other.real; result.image = image - other.image; return result; }

// 重载求负运算符(一元) COMPLEX COMPLEX::operator-() { COMPLEX result; result.real = -real; result.image = -image; return result; }

// 重载赋值运算符(二元) COMPLEX COMPLEX::operator=(const COMPLEX &other) { real = other.real; image = other.image; return *this; }

// 重载前置++ COMPLEX & COMPLEX::operator++() { real++; return *this; }

// 重载后置++ COMPLEX COMPLEX::operator++(int) { COMPLEX temp(*this); real++; return temp; }

// 重载前置-- COMPLEX & COMPLEX::operator--() { real--; return *this; }

// 重载后置-- COMPLEX COMPLEX::operator--(int) { COMPLEX temp(*this); real--; return temp;

实现复数的操作符重载你需要做的是将complexh文件的函数声明全部在complexcpp中实现。类的声明如下:class COMPLEXpublicCOMPLEXdouble r = 0 double i = 0; 构造函数COMPLEXconst COMPLEX &other; 拷贝构造函数void print; 打印复数 重载加法运算符二元COMPLEX operator+const

原文地址: https://www.cveoy.top/t/topic/hFGs 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录