使用 C++ 实现向量,并重载运算符对其进行基本运算;
将以下四个文件放入同一文件夹中,对 main.cpp 执行编译即可;
本人萌新,评论区欢迎各位大佬提问、指正;
Complex.h
#ifndef COMPLEX_H_
#define COMPLEX_H_
#include <iostream>
using std::istream;
using std::ostream;
class Complex
{
private:
double real;
double image;
public:
Complex();
Complex(double x, double y);
// OPOL: operator overloading
// operator +
Complex operator+(const Complex &c) const; // complex + complex
Complex operator+(double n) const; // complex + real
friend Complex operator+(double n, const Complex &c); // real + complex
// operator -
Complex operator-(const Complex &c) const; // complex - complex
Complex operator-(double n) const; // complex - real
friend Complex operator-(double n, const Complex &c); // real + complex
Complex operator-() const; // -complex
// operator *
Complex operator*(const Complex &c) const; // complex * complex
Complex operator*(double n) const; // complex * real
friend Complex operator*(double n, const Complex &c); // real * complex
// operator >>
friend istream &operator>>(istream &is, Complex &c); // cin >> complex
// operator <<
friend ostream &operator<<(ostream &os, const Complex &c); // cout << complex
};
#endif
Complex.cpp
#include <iostream>
#include "Complex.h"
Complex::Complex()
{
real = image = 0.0;
}
Complex::Complex(double x, double y)
{
real = x;
image = y;
}
OPOL.cpp
// operator overloading
#include <iostream>
#include "Complex.h"
using std::istream;
using std::ostream;
ostream &operator<<(ostream &os, const Complex &c)
{
os << c.real << " + " << c.image << "i";
return os;
}
istream &operator>>(istream &is, Complex &c)
{
// can't use const here
is >> c.real >> c.image;
return is;
}
Complex Complex::operator+(const Complex &c) const
{
Complex result;
result.real = real + c.real;
result.image = image + c.image;
return result;
}
Complex Complex::operator+(double n) const
{
Complex result;
result.real = real + n;
result.image = image;
return result;
}
Complex operator+(double n, const Complex &c)
{
return c + n;
}
Complex Complex::operator-(const Complex &c) const
{
return *this + (-c);
}
Complex Complex::operator-(double n) const
{
return *this + (-n);
}
Complex operator-(double n, const Complex &c)
{
return n + (-c);
}
Complex Complex::operator-() const
{
Complex result;
result.real = -real;
result.image = -image;
return result;
}
Complex Complex::operator*(const Complex &c) const
{
Complex result;
result.real = real * c.real - image * c.image;
result.image = image * c.real + c.image * real;
return result;
}
Complex Complex::operator*(double n) const
{
Complex result;
result.real = real * n;
result.image = image * n;
return result;
}
Complex operator*(double n, const Complex &c)
{
return c * n;
}
main.cpp
#include <iostream>
#include "Complex.h"
#include "Complex.cpp"
#include "OPOL.cpp"
using namespace std;
int main()
{
Complex C1 = {2, 2};
Complex C2 = {1, 1};
// ...
while(true)
cin.get();
return 0;
}