c++ - 二进制运算符实现为静态成员函数

标签 c++

所以在我的书上写着:

The definition of a binary operator implemented as a global function or a static member function is the following: return_type operator_type (parameter1, parameter2);



现在我不明白作者的意思是

static member function



我如何理解这是static类中的运算符重载,我认为这是不可能的,我不明白...

我不能这样做:

class Test {
//data attributes
public:
   static Date operator+(Date& lhs, Date& rhs) {
        //implementation code
    }
}

因为如果这样做,我会得到一个错误:Overloaded 'operator+' cannot be a static member function

那么这是一个错误还是我误解了?

提前致谢。

最佳答案

在C#中,运算符是静态成员函数,但在C++中(与您的书相反),它们是表达式左侧的类的顶级(全局)或非静态成员,在此为Date案件:

class Date {
//data attributes
public:
   Date operator+(const Date& rhs) const {
        //implementation code
    }
}

注意两个const,因为添加的两个参数都没有被它更改。

关于c++ - 二进制运算符实现为静态成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61368744/

相关文章:

c++ - 计算出保存一个 int 需要多少字节的算法

c++ - 队列不添加对象 - C++ 11

c++ - ld : duplicate symbol

C++ - 值意外更改

c++ - 为什么没有发生隐式转换

c++ - 获取指定时区的日期和时间

c++ - VerticalIntensityStatistics 类似于 OpenCV

c++ - 将一个 channel 数据复制到Opencv中的另一个 channel

c++ - 重载 operator= 不起作用

c++ - 获取下一个不连续的二进制数