我在一个Cpp初学者项目。建立一个图书馆系统。我写了下面的void Student::show(void)函数来显示学生的详细信息。我还写了第一个函数,以避免重复。我想把create函数作为参数传递给printAtEnd函数。但是它给了我一些错误。我做错了什么。
// conclusion menu
template <typename R, typename A, typename C>
// R - return type
// A - argument type
// C - class type
void printAtEnd(R (C::*func)(A)){
int i;
cout << "Choose one of following.\n";
cout << "\t1. go to main menu.\n";
cout << "\t2. try again.\n";
cout << "\t3. exit the program\n";
cin >> i;
switch(i){
case 1: mainMenu(); break;
case 2: func(); break;
case 3: exit(0); break;
}
}
void Student::show(void){
system("clear");
cout << "\tStudent details\n\n";
cout << "Name: " << name << endl;
cout << "Addmission No: " << addmission_no << endl;
cout << "Email: " << email << endl;
cout << "Telephone No: " << telephone_no << endl;
cout << "Issued books: \n";
for (string x: issued_books)
cout << x << endl;
printAtEnd<void, void, Student>(&Student::show);
}
我在编译时得到以下错误。
library.cpp: In member function ‘void Student::show()’:
library.cpp:151:36: error: no matching function for call to ‘printAtEnd<void, void, Student>(void (Student::*)())’
151 | printAtEnd<void, void, Student>(&Student::show);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
library.cpp:79:6: note: candidate: ‘template<class R, class A, class C> void printAtEnd(R (C::*)(A))’
79 | void printAtEnd(R (C::*func)(A)){
| ^~~~~~~~~~
library.cpp:79:6: note: template argument deduction/substitution failed:
library.cpp: In substitution of ‘template<class R, class A, class C> void printAtEnd(R (C::*)(A)) [with R = void; A = void; C = Student]’:
library.cpp:151:36: required from here
library.cpp:79:6: error: invalid parameter type ‘void’
library.cpp:79:6: error: in declaration ‘void printAtEnd(R (C::*)(A))’
我想要的是在每个其他函数之后调用printAtEnd函数。所以我需要将指向函数的指针传递给printAtEnd函数。
###从问题中删除无用的代码可以是这样的:
void printAtEnd(std::function<void ()> fn)
{
fn();
}
void Student::show()
{
printAtEnd([this](){ this->show(); });
}
然而,你的代码的问题是,它是递归的,如果用户总是选择选项2,你可能最终得到堆栈溢出,如果你运行在一些小的内存设备。
在这种情况下,循环通常是一个更好的选择。