2016-11-23 68 views
0

請幫助我... 我有Student類,LinkedList類和struct Node。我想要獲得學生的(對象)名稱,我有這麼多的錯誤。我不知道調用函數的typedef。通過鏈表類中的另一個類調用函數

有我的代碼:

#include <iostream> 
#include <string> 

using namespace std; 

class Student{ 
public: 
string name; 
int age; 
Student(string n, int a){ 
    name = n; 
    age = a; 
} 
Student(){}; 

void showname(){ 
    cout << "My name is: " << name << endl; 
} 

void showage(){ 
    cout << "My age is: " << age << endl; 
} 
}; 

template<class T>struct Node{ 
    T value; 
    Node<T>* next; 
}; 

template<class T>class LinkedList{ 
     typedef void (T::*fn)(); 
    public: 
     Node<T>* first; 
     Node<T>* temp; 
     LinkedList(){ 
      first = NULL; 
     } 

    void insert(T a2){ 
     Node<T>* new_node = new Node<T>; 
     new_node->value = a2; 
     new_node->next = first; 
     first = new_node; 
    } 

    void call(T b, fn op){ 
     (b.*op)(); 
    } 

    void show(){ 
     temp = first; 
     while(temp!=NULL){ 
      cout << temp->value; 
      temp = temp->next; 
     } 
     cout << endl; 
    } 
}; 

int main(){ 
    Student s1("Nurbolat", 18); 
    int a = 1; 
    LinkedList<int> l1; 
    LinkedList<Student> l2; 
    l2.call(s1, &Student::showname); 
    l2.call(s1, &Student::showage); 
    return 0; 
} 

回答

2
typedef void (T::*fn)(); 

創建別名fn作爲T類型的成員函數,不接收參數和返回void

由於int是簡單類型,它不」沒有任何成員函數。

這不是必需的,但它允許實例化所有成員函數LinkedList,然後LinkedList<int>可能會給出錯誤。

刪除的typedef並替換:

void call(T b, fn op){ 
    (b.*op)(); 
} 

有:

template <typename F> 
void call(T b, F op){ 
    (b.*op)(); 
} 

,那麼它應該工作

+0

它的工作。非常感謝你) –

相關問題