所以在我的书上写着:
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/