我试图重载运算符 % 因为你不能对 double 类型使用模数,
float a = 5.0;
float b = 5.0;
a = a % b;
// not allowed
我试图用这种函数重载运算符 % :
template <>
MyClass* MyClass<float>::operator%(Myclass &other)
对于其他不涉及 float 的操作,我使用:
template <class T>
MyClass* MyClass<T>::operator%(MyClass &other)
实际上它从未编译过我被卡住了,找不到绕过这个问题的方法, g++ 仍然警告我你不能对 float 执行模运算,这是错误的 使用我的模板语法还是真的不可能。
最佳答案
您不能按照您希望的方式重载原始类型的运算符。
对于 C++11 草案 n3290,§13.5 运算符重载,第 6 点:
An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration. [...]
基本类型不是类(或枚举),因此它们不能有成员函数。而且您无法创建全局 float operator%(float&,float&)
因为这不涉及参数列表中的类或枚举。 (另见 C++FAQ 26.10 "Can I define an operator overload that works with built-in / intrinsic / primitive types?"。)
您至少需要 %
中的一项表达式成为用户定义的类型。
您可以创建一个类 Float
并定义你想要的任何操作,但你无法获得 a = a % b;
使用你的功能,如果a
和 b
是 float
或者你可以 #include <cmath>
并使用 std::fmod
:
#include <iostream>
#include <cmath>
int main()
{
float a = 13.0f;
float b = 5.0f;
a = std::fmod(a, b);
std::cout << a << std::endl;
return 0;
}
带有自定义“ float 包装器”的简单示例(不完整,可能不太安全,但可以帮助您入门):
#include <iostream>
#include <cmath>
class Float {
private:
float val;
public:
Float(float f): val(f) {};
Float operator%(Float const& other) const {
return std::fmod(val, other.val);
}
Float operator%(float const& other) const {
return std::fmod(val, other);
}
// conversion operator could be handy
operator float() { return val; }
};
int main()
{
Float a = 13.0f;
Float b = 5.0f;
Float c = a % b;
std::cout << c << std::endl;
// this also works
Float d = 13.0f;
float e = 5.0f;
float f = d % e;
std::cout << f << std::endl;
return 0;
}
关于c++ - 为 float 类型重载 operator%,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9201497/