c++ - 如何将函数指针的 std::vector 初始化为运算符重载?

标签 c++ operator-overloading c++14 pointer-to-member

我试图用指向四个运算符重载成员函数的指针制作一个 std::vector。这有什么问题:

struct Fractal
{   int dividee;
    int divisor;

    Fractal operator +(Fractal other)
    {   [not important]
    }

    Fractal operator -(Fractal other)
    {   [not important]
    }

    Fractal operator *(Fractal other)
    {   [not important]
    }

    Fractal operator /(Fractal other)
    {   [not important]
    }
};

int main()
{   Fractal fractal = Fractal{3, 10};

    typedef Fractal(*fractalOperator)(Fractal, Fractal);
    std::vector<fractalOperator> ops =
    {   &Fractal::operator +,
        &Fractal::operator -,
        &Fractal::operator *,
        &Fractal::operator /
    };
}

编译器说

error: could not convert '{&Fractal::operator+, &Fractal::operator-, &Fractal::operator*, &Fractal::operator/}' from '<brace-enclosed initializer list>' to 'std::vector<Fractal (*)(Fractal, Fractal)>'
 };

这不是很有帮助。什么是正确的方法?我正在使用 C++14。

最佳答案

您的 typedef 用于指向函数的指针,该函数采用两个 Fractal 并返回一个 Fractal。你想要的是 pointer to member function , 它有不同的语法。

typedef Fractal(Fractal::*fractalOperator)(Fractal);

或者,使用 using 别名,我觉得这样更容易阅读

using fractalOperator = Fractal(Fractal::*)(Fractal);

关于c++ - 如何将函数指针的 std::vector 初始化为运算符重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50217236/

相关文章:

c++ - 我可以在 lambda 捕获子句中声明一个变量吗?

c++ - 如何在 linux 中的多个应用程序中共享库中的变量?

c++ - 如何为具有交换功能的双向链表创建冒泡排序?

c++ - 重载 + 运算符的级联

f# - F# "remove a lot of subtle bug"如何来自 OCaml "+"?

c++ - 当不应调用构造函数时,复制参数会调用已删除的构造函数

c++ - 为什么不能使用 C++ 异常处理异步事件?

c++ - 迭代器库的正面和背面提案

c++ - 将复数运算符+(double,complex) 实现为成员函数

c++ - L 和 R 引用变量