简体   繁体   English

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

[英]Call function from another class in main via linkedlist class

Please, help me... I have Student class, LinkedList class and struct Node. 请帮帮我...我有Student类,LinkedList类和struct Node。 I want to get Student's(object) name in main and I have so many errors. 我想在主目录中获得学生的(对象)名称,并且有很多错误。 I'm not understanding typedef for calling the function. 我不了解typedef调用该函数。

There my code: 有我的代码:

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

create an alias fn as a member function of type T , receives no parameter and return void 创建别名fn作为类型T的成员函数,不接收任何参数并返回void

Since int is a primitive type, it doesn't have any member function. 由于int是原始类型,因此它没有任何成员函数。

It's not required but it's allowed to instantiate all member function of LinkedList , then LinkedList<int> may give an error. 它不是必需的,但允许实例化LinkedList所有成员函数,然后LinkedList<int>可能会给出错误。

Remove that typedef and replace: 删除该typedef并替换:

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

with: 与:

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

then it should works 那么它应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM