c++ - 运算符重载和非成员函数 c++

标签 c++ operator-overloading non-member-functions

我已经为复数编写了一个类,其中重载了运算符 + 并且一切正常,但是我需要将其实现为非成员函数,我不确定如何或为什么有好处这样做。

这是我的代码.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/

相关文章:

c++ - 为类中的自定义类型重载 operator=

c++ - 参数化运算符重载

c++ - 为什么 boost 推荐使用核心函数而不是成员函数?

c++ 在运算符重载函数中创建、分配新变量并将其与两个对象进行比较。

c++ - 'operator==' 具有自己的类和 std::string_view 的不明确重载

c++ - Windows/C++ : how can I get a useful stack trace from a signal handler?

java - 任务间的 OpenCL 共享内存

c++ - WSARecv 如何使用 lpOverlapped?我怎样才能手动发出事件信号?

c++ - Ostream << 运算符重载及其返回类型

c++ - 私有(private)成员(member)和免费功能的 Doxygen 评论?