c++ - 通过链表类从 main 中的另一个类调用函数

标签 c++ templates linked-list

请帮帮我... 我有 Student 类、LinkedList 类和结构节点。我想在 main 中获取学生的(对象)名称,但我有很多错误。我不理解调用函数的 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;
}

最佳答案

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

那么它应该可以工作了

关于c++ - 通过链表类从 main 中的另一个类调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756174/

相关文章:

对我在面试中看到的这段 C 代码感到困惑

c++ - VC++改变桌面背景的方法

c++ - 从 Homography 矩阵计算比例、旋转和平移

C++ std::pair代码理解

c++ - 确定结构是否具有特定类型的成员

c - 用额外的释放数据销毁c中的链表

c++ - Qt:单实例应用保护的最佳实践

c++ - 模板和常量

java - Eclipse Java 编辑器模板...为什么没有类型变量?

c++ - 给定一个节点数为奇数的单链表,通过只遍历链表一次找到中间节点的两种方法是什么?