C++ 从友元类调用成员函数指针

问题描述 投票:0回答:1
class classA {
public:
    classA() { 
        if (condition) { cp = &classA::Add; }
        else { cp = &classA::Mul; }
    }
private:
    typedef int (classA::*ComputeMethod)(int x, int y);
    int Add(int x, int y) { return x+y; }
    int Mul(int x, int y) { return x*y; }
    ComputeMethod cp;
    friend class classB;
};

class classB {
public:
   void Compute(int x, int y) { (a.*cp)(x,y); } // why this does not compile?
private:
    classA a;
};

如上面的代码,为什么classB中的Compute方法无法编译?编译器说“间接要求指针操作数“ComputeMethod”无效”。

请帮助我。

c++ function-pointers
1个回答
0
投票

它有效。但是……很奇怪

如果它不可读,你可以使用

std::invoke
与 c++17:

std::invoke(a.cp, a, x,y); //compiles 
(a.*a.cp)(x,y);            //old style compiles
© www.soinside.com 2019 - 2024. All rights reserved.