我已经为复数编写了一个类,其中重载了运算符 + 并且一切正常,但是我需要将其实现为非成员函数,我不确定如何或为什么有好处这样做。
这是我的代码.h:
class Complex
{
private:
double a;
double b;
public:
Complex();
Complex(double aGiven);
Complex(double aGiven, double bGiven);
double aGetValue();
double bGetValue();
double operator[](bool getB);
Complex add(Complex &secondRational);
Complex operator+(Complex &secondRational);
}
.cpp:
Complex Complex::add(Complex &secondRational)
{
double c = secondRational.aGetValue();
double d = secondRational.bGetValue();
double anew = a+c;
double bnew = b+d;
return Complex(anew,bnew);
}
Complex Complex::operator+(Complex &secondRational)
{
return add(secondRational);
}
任何有关如何将这些作为非成员函数的帮助将不胜感激!
最佳答案
下面是类外的加法运算符:
Complex operator+(const Complex& lhs, const Complex& rhs) {
//implement the math to add the two
return Complex(lhs.aGetValue() + rhs.aGetValue(),
lhs.bGetValue() + rhs.bGetValue());
}
当然,您需要将 aGetValue()
和 bGetValue()
声明为 const
:
double aGetValue() const {return a;}
double bGetValue() const {return b;}
关于c++ - 运算符重载和非成员函数 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281352/