C++代码报undefined reference to info()错误的修复咨询
编译错误修复方案
问题概述
编译时出现未定义引用错误:
undefined reference to `info(std::__cxx11::basic_string<char, std::char_traits
, std::allocator >*, int, int)'
任务要求:用三个数组实现员工参会标记,禁止使用指针、引用或结构体。
错误根源
info函数的声明与定义参数不匹配:
- 声明时第一个参数是字符串数组:
bool info(string Names[10], int num, int pos); - 定义时却写成了单个字符串:
bool info (string Names, int num, int pos)
编译器根据声明找对应的实现,结果找不到匹配的函数,因此报出未定义引用错误。
核心修复步骤
修改info函数的定义,把第一个参数改为字符串数组:
bool info (string Names[10], int num, int pos) { string s; bool choice; if (num == 0) { s = "SESSION A"; } else if (num == 1) { s = "SESSION B"; } // 修复输入提示的空格问题,避免姓名与提示语连在一起 cout << (pos + 1) << ". " << Names[pos] << " are they going to attend " << s << "(1-accept / 2-decline): "; cin >> num; if (num == 1) { choice = true; } else if (num == 2) { choice = false; } return choice; }
额外修复(避免运行时错误)
- 修复
display函数的输出问题
原代码用printf输出C++字符串和布尔值会出现格式错误,改用cout配合格式化输出更适配:
void display (string Names[10], bool sesA[10], bool sesB[10]) { cout << left << setw(3) << "#" << setw(20) << "Attendee" << setw(12) << "Session A" << "Session B" << endl; for (int i = 0; i < 10; i++) { cout << left << setw(3) << (i+1) << setw(20) << Names[i] << setw(12) << (sesA[i] ? "Yes" : "No") << (sesB[i] ? "Yes" : "No") << endl; } }
并在主函数的totalAttendees调用前添加:
display(arrNames, SessionA, SessionB);
- 修复
totalAttendees的计数逻辑
原逻辑会把同时参加两场的员工重复计数,简化为只要参加任意一场就计数一次:
void totalAttendees (bool sesA[10], bool sesB[10]) { int total = 0; for (int i = 0; i < 10; i++) { if (sesA[i] || sesB[i]) { total++; } } cout << "\nThe total Attendees: " << total; }
内容的提问来源于stack exchange,提问作者WD de Wet
相关产品推荐
相关产品推荐

