我试图使用指向成员函数的指针通过链表进行动态访问。 (几个月以来我一直在学习C ++)
A上了一堂课。类的构造函数建立一个链表。每个节点包含一些数据,指向下一个节点的指针以及指向函数的指针a(我正在尝试最后一个……暂时不起作用)
我能够在构造函数中使用指向成员函数的指针,但我不理解如何将此指针值传递给其他结构或函数。也许我想念一些简单的事情...
预先感谢您的帮助。
尝试对成员函数的指针使用正确的语法
尝试一些不同的语法将值作为参数传递给函数
class linkedFct{
private:
struct node *firstNode;
struct node *lastNode;
struct node *newNode;
struct node *currentNode;
public:
linkedFct(){
firstNode = (NULL);
lastNode = (NULL);
void (linkedFct::*ptrFct)();
ptrFct = &linkedFct::theFunctionA;
//Call the function by pointer... this works!!! Great!
(this->*ptrFct)();
//Add a first node to the list
addNode("Try a first task");
//addNode("Try a first task", &(this->*ptrFct()));
//Trying to include the member function pointer into the list data
//this is not working!!! Don't understand how to pass that pointer
//to a member function
}
void addNode(string aName){
//void addNode(string aName, void (linkedFct::*ptrF)()){
//I am trying to implement something like this
//Trying to pass a member function pointer thru this attribute
newNode = new node;
newNode->name = aName;
//newNode->ptrFunction = ptrF; //Trying to implement something like this***
lastNode = newNode;
if (!firstNode){
firstNode = newNode;
}
else{
currentNode->nextNode = newNode;
}
currentNode = newNode;
};
尝试使用列表中的指针... mmm ...不能正常工作
void processTheList(){ //Browse the list
struct node *thisCurrentNode;
void (linkedFct::*ptrRunFct)();
thisCurrentNode = firstNode; //Start from top
int i = 0;
while (thisCurrentNode){
i++;
cout << "Node #" << i << ": Name: " << thisCurrentNode->name << endl; //Print the string
ptrRunFct = thisCurrentNode->ptrFunction;
ptrRunFct();
cout << endl;
thisCurrentNode = thisCurrentNode->nextNode;
}
}
节点结构是这样定义的:
struct node{ //A node struct to implement a linked list
string name; //Some data
void (linkedFct::*ptrFunction)(); //A pointer to member function... ****[That's what I am trying!!!]****
struct node *nextNode; //Pointer to next node
};