通过linkedlist类从main中的另一个类调用函数

时间:2016-11-23 04:40:57

标签: c++ templates linked-list

请帮帮我... 我有Student类,LinkedList类和struct Node。我想在main中获得Student的(对象)名称,并且我有很多错误。我不理解调用该函数的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;
}

1 个答案:

答案 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)();
}

那么它应该有效

相关问题