gpt4 book ai didi

c++ - 如何从 C++ 中实例化对象的函数指针调用函数?

转载 作者:行者123 更新时间:2023-11-27 22:34:36 25 4
gpt4 key购买 nike

我有两个类,SimIElementIElement 类定义了一个函数指针,而 Sim 类有一个 IElement 指针 vector 。如果我有一个 IElement* vector ,从 IElement 中定义的函数指针调用指向函数的正确方法是什么?

换句话说,我有

std::vector<IElement*> nodes;

我需要从 IElement 调用一个指向的函数:

nodes[i]->*SetInput(); // ERROR: Identifier "SetInput" is undefined

我假设我有这个错误,因为 nodes 是一个指针 vector ,而且我不知道如何在调用它的 pointed- 之前取消引用 nodes[i]发挥作用。

感谢您的任何建议。

下面给出了更详细的代码片段。

Sim 类的方法,我对 IElement 的方法有错误 Undefined identifier

#include <vector>
#include "Elements.h" // defines class IElement in namespace Elements
void Sim::CreateNodes(int N) // this method belongs to the Sim class in namespace "Simulations"
{
nodes = std::vector<Elements::IElement*>(N);
int i = 0;
while (i < N)
{
nodes[i] = new Elements::IElement(true); // for the sake of the example
nodes[i]->*SetInput(); // ERROR: Identifier "SetInput" is undefined
i++;
}
}

而在 Elements 命名空间中,我有类 IElement 声明

class IElement
{
public:
typedef void(IElement::*SetInputFc_ptr)();
IElement(bool); // normalizeInput
~IElement();
SetInputFc_ptr SetInput;
};

和类IElement实现

IElement::IElement(bool normalizeInput)
{
if (normalizeInput)
{
this->SetInput= &(this->SetInput_Sum);
}
else
{
this->SetInput= &(this->SetInput_Const);
}
}

最佳答案

您需要使用普通成员运算符从 IElement 对象中获取 SetInput 成员值,然后调用 IElement< 上的成员函数 对象,使用 ->*。假设您要对两者使用相同的 IElement:

(nodes[i]->*(nodes[i]->SetInput))();

或者也许将这对语句重写为:

Elements::IElement* node = Elements::GetElement(i);
nodes[i] = node;
(node->*(node->SetInput))();

顺便说一句,&(this->SetInput_Sum) 不是获取指向成员的指针的官方有效方法。如果你的编译器接受它,它允许它作为一个扩展。 IElement 构造函数应该这样写:

IElement::IElement(bool normalizeInput)
{
if (normalizeInput)
{
this->SetInput= &IElement::SetInput_Sum;
}
else
{
this->SetInput= &IElement::SetInput_Const;
}
}

关于c++ - 如何从 C++ 中实例化对象的函数指针调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com