[問題] 在class使用函式指標陣列

看板C_and_CPP作者 (ET)時間10年前 (2013/11/02 00:39), 編輯推噓2(2011)
留言13則, 6人參與, 最新討論串1/1
在 win 7 中用記事本寫,寫完後用cmd 的g++ 來compile 問題: 想在class中練習函式指標陣列,卻怎麼也改不掉error 檔案 linkList.h 如下 #ifndef LINKLIST_H #define LINKLIST_H class Node { public: Node(); Node(int , Node *); Node* insert(Node *); Node* print(Node *); private: int data; Node *next; }; #endif 檔案 linkList.cpp 如下 #include<iostream> using std::cout; using std::cin; using std::endl; #include<cstdlib> #include<ctime> #include"linkList.h" Node::Node() { data = 0; next = NULL; } Node::Node(int d, Node *n) { data = d; next = n; } Node* Node::insert(Node *listPtr) { srand( time(0) ); Node *newnode = new Node( rand()%100 + 1, NULL); Node *temp = listPtr; if( listPtr == NULL) listPtr = newnode; else { while( temp->next != NULL ) temp = temp->next; temp->next = newnode; } return listPtr; } Node* Node::print(Node *listPtr) { while( listPtr->next != NULL ) { cout << " " << listPtr->data << ","; listPtr = listPtr->next; } cout << " " << listPtr->data << endl << endl; return listPtr; } 檔案 main.cpp 如下 #include<iostream> using std::cout; using std::cin; using std::endl; #include<cstdlib> #include<ctime> #include"linkList.h" int main() { Node *head = NULL; int func; while(true) { cout << " please enter the #func. : " ; cin >> func; //Node* (*funcPtr[2])(Node *) = {head->insert, head->print}; Node* (Node::*funcPtr[2])(Node *)={&Node::insert,&Node::print}; ( *funcPtr[func] )( head );//??? 這一行有一個error ???? //head = head->insert( head ); //head->print( head ); } exit( EXIT_SUCCESS); return 0; } 原本是單純練習class 後來為了要加上 函式指標陣列 的方式 所以就不斷修改 改到最後,在許多問號那一行有一個error 在cmd輸入g++ linkList.h linkList.cpp main.cpp 錯誤訊息如下 main.cpp:25:18: error: invalid use of unary '*' on pointer to member ( *funcPtr[func] )( head ); ^ 是有先google過,但google後的結果卻還是看不出個所以然 所以只好又摸摸鼻子,來版上懇請各位前輩相救 又給各位前輩帶來麻煩了 希望前輩能夠狠狠地給予打臉指導 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.167.75.80 ※ 編輯: aaqqaaqq 來自: 118.167.75.80 (11/02 00:42)

11/02 00:43, , 1F
不需要前面那個*
11/02 00:43, 1F

11/02 00:43, , 2F
( funcPtr[func] )( head ) 即可
11/02 00:43, 2F

11/02 00:45, , 3F
不加*也會錯,錯誤如下:
11/02 00:45, 3F

11/02 00:46, , 4F
must use'.*'or'->*'to call pointer-to-member function
11/02 00:46, 4F

11/02 00:47, , 5F
in 'funcPtr[func] (...)',
11/02 00:47, 5F

11/02 00:47, , 6F
e.g. '(... ->* funcPtr[func]) (...)'
11/02 00:47, 6F

11/02 00:48, , 7F
( funcPtr[func] )( head ); 以上這是錯誤訊息
11/02 00:48, 7F

11/02 01:32, , 8F
已經可以列入FAQ的常見新手錯誤
11/02 01:32, 8F

11/02 01:32, , 9F
成員函式指標和一般的函式指標不同
11/02 01:32, 9F

11/02 01:33, , 10F
你必需提供一個 object 才能呼叫成員函式指標
11/02 01:33, 10F

11/02 14:10, , 11F
aaqqaaqq: 錯誤訊息看起來很明顯阿 XD.
11/02 14:10, 11F

11/02 15:53, , 12F
這個主題好像剛剛大吵一波過(?)
11/02 15:53, 12F

11/02 18:29, , 13F
嚴格來說後來大吵的東西跟這個主題沒有關係了 (?
11/02 18:29, 13F
文章代碼(AID): #1ISzb5bQ (C_and_CPP)