我可以在类中重载静态运算符吗
Can I overload static operator in a class?
在C#中,要重载诸如"+"、"-"等运算符,我必须使函数成为类的静态成员:
class MyType
{
/*...*/
public static MyType operator+ (MyType a, MyType b)
{
MyType ret;
/* do something*/
return ret;
}
}
据我所知,在C++中,这就是我如何重载运算符的方法:
class MyType
{
/*...*/
public:
MyType operator+ (MyType b) // *this is the first operand
{
MyType ret;
/* do something*/
return ret;
}
};
问题是*this
是第一个操作数,因此第一个操作的类型必须是MyType。例如,如果我想将MyType
添加到一个整数:
MyType a, b;
b = a + 1; // Valid
b = 1 + a; // Error
在C#中,我可以为每种情况重载"+"运算符。
我的问题是:我能在C++中像在C#中一样使用静态运算符吗?据我所知,有一种方法可以做到这一点,使用友元运算符,但在继承函数时会丢失它们。
使左侧int
的operator+
重载为自由函数,而不是MyType
:的成员函数
class MyType
{
...
// MyType + int can be a member function because MyType
// is the type of the sum's left hand side
MyType operator+(int rhs) const;
};
// int + MyType needs to be a free function because
// int is the type of the sum's left hand side
MyType operator+(int lhs, const MyType &rhs);
另一个常见的习惯用法是使重载成为感兴趣类的friend
。现在,您可以用相同的方式实现这两种情况:
class MyType
{
...
friend MyType operator+(int lhs, const MyType &rhs)
{
// get access to MyType's private members here
// to implement the sum operation
...
}
friend MyType operator+(const MyType &lhs, int rhs)
{
// you can also implement the symmetric case
// of int on the right hand side here
...
}
};
请注意,尽管operator+
重载看起来像第二个示例中的成员函数,但由于它们声明为MyType
的friend
s,因此它们实际上是全局范围内的自由函数。
您可以在C++中的全局作用域中定义运算符,例如
MyType operator+ (const MyType& a, const MyType& b)
{
MyType ret;
/* do something*/
return ret;
}
如果操作员应该访问类的私有成员,则可能需要向MyType
添加友元声明。
相关文章:
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 将私有结构哈希器运算符转换为静态
- 是否应该在复制构造函数或赋值运算符中复制静态数据成员
- 重载运算符和静态成员变量的行为
- 调用非静态函数的重载括号运算符
- 将对象数限制为1可以使用点运算符访问静态成员的1
- 静态与成员运算符重载:标准::运算符<< 和 std::ostream::运算符<<
- 错误:非静态引用成员"std::ostream&Student::out",无法使用默认赋值运算符
- 重载运算符时出错(必须是非静态成员函数)
- 存在静态常量成员时的赋值运算符
- 运算符"="必须是非静态成员函数错误
- 我可以在类中重载静态运算符吗
- LNK4221:运算符<<重载未导出到静态库中
- 静态指针和运算符新增
- 错误:非静态引用成员,无法使用默认赋值运算符
- 为什么重载运算符不能定义为类的静态成员
- 在派生类中使用提取运算符(>>)的方法以及在C++中处理静态数据成员的方法
- 使用 new 运算符静态分配对象
- 非成员运算符 == 我可以将其设为静态吗?
- 如何定义静态运算符<<?