c++ - 为 float 类型重载 operator%

标签 c++ templates g++

我试图重载运算符 % 因为你不能对 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;使用你的功能,如果abfloat

或者你可以 #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/

相关文章:

c++ - Koenig 查找的基本原理

css - Custom.css 未在 PrestaShop 1.7 中运行

c++ - 如何使用 Visual Studio Code 从 Visual Studio 2019 构建、调试和运行现有 C++ 解决方案 (.sln)?

c++ - 自定义 std::shared_ptr 或 boost::shared_ptr 以在 NULL 取消引用时抛出异常

c++ - 访问栈和堆哪个更快?

c++ - 大量 LNK2005 错误

c++ - 意外的模板扣除

c++ - VC++ 6.0 中的 Cfitsio 错误

c++ - RVO/NRVO 和公共(public)未定义复制构造函数

c++ - 使用 g++ 4.6.1 我在尝试包含 xaudio2.h 时遇到许多 C++ 编译错误