调用与父类函数指针同名的函数

时间:2015-08-14 01:07:30

标签: c++ function function-pointers

我正在尝试使用各种Nodes来运行定义的execute函数,该函数传递给构造函数并从函数指针变量中存储(和调用)。

class Node{
    std::string(*execute)();
};

Node::Node(std::string(*funcPointer)()){
    execute = funcPointer;
}

我还有几个派生类,它们都有execute功能

class redNode : public Node{
    std::string execute();
};

std::string redNode::execute(){
    return "I'm red";
}

class blueNode : public Node{
    std::string execute();
};

std::string blueNode::execute(){
    return "I'm red";
}

然后,我想调用所有Node的execute函数。

std::string myFunc(){
     return "my Func";
}

Node mynode = new Node(&myFunc);
//other instantiations here...

myRedNode.execute();
myBlueNode.execute();
myNode.execute();

但是,尝试调用.execute()myRedNode的{​​{1}}不起作用,因为父类的一部分myBlueNode变量从未设置过,似乎打电话给那个。然后尝试设置execute变量

execute

给出一个myBlueNode.execute = &BlueNode::execute; ,即使我重命名我将变量设置为的函数。

我该如何解决这个问题?如何使用与父类函数指针相同的名称正确调用函数?

2 个答案:

答案 0 :(得分:1)

&BlueNode::execute不仅仅是一个函数指针。它是一个成员函数指针。它可以通过这种方式使用:

std::string (BlueNode::*pf)();
pf = &BlueNode::execute;

BlueNode obj;
(obj.*pf)();

但是这会强制该功能成为特定类的成员,我认为你不想要它(如果是这样,你只需要使用虚函数。)

我建议使用std::function<>

class Node
{
    std::function<std::string()> execute;
public:
    Node(std::function<std::string()> _execute)
        : execute(std::move(_execute))
    {
    }
};

您可以使用普通函数,成员函数,仿函数和lambda。

std::string f1() { return "f1"; }
struct T { std::string f2() { return "f2"; } };
struct F { std::string operator ()() const { return "f3"; } };

T obj;
Node n1 { f1 };
Node n2 { std::bind(&T::f2, &obj) };
Node n3 { F() };
Node n4 { []() { return std::string("f4"); } };

(live example)

答案 1 :(得分:1)

首先,&BlueNode::execute不是函数指针,它是指向成员函数的指针。对你&BlueNode::execute你还需要一个类指针来使用它。例如:

std::string (BlueNode::*memberFunctionPointer)();
memberFunctionPointer = &BlueNode::execute;

BlueNode blueNode;
(blueNode.*memberFunctionPointer)();

要执行您想要的操作(在父级中设置一个变量来调用任意函数),您需要使用std::functionstd::bind来收集实例和成员函数指针,其中@ikh已经解释过,或者如果那不是你真正想做的事情,你也可以将父对象中的指针更改为成员函数指针并在子实例上调用它,或者你可以使用虚函数自动执行。

现在你遇到了第二个问题,为什么当你尝试error C2659: '=' function as left operand时给它myBlueNode.execute = &BlueNode::execute;是因为派生类方法execute隐藏了父变量{{1} }}。要访问隐藏变量,您需要通过强制转换将对象作为父类型来访问。这是一个例子,只使用一个独立的功能:

execute

IDEONE

相关问题