[英]Accessing a private struct LinkedList in another Class via function;
[英]Call function from another class in main via linkedlist class
請幫幫我...我有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;
}
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)();
}
那么它應該工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.