C++使用友元函数重载输入输出运算符报未定义引用错误
Section_401k类运算符重载链接报错排查
核心报错原因
你在Section_401k类内仅声明了operator<<、operator>>的友元重载,但从未实现这两个函数,链接器找不到对应函数的二进制符号,直接抛出undefined reference错误,无法生成可执行文件。
除此之外代码还存在两处逻辑问题,就算解决了链接报错,运行结果也完全不符合预期:
applyPercentage()、computeTotalAccountValue()函数内部都定义了局部临时对象anEmployee,所有输入、计算操作都作用在这个临时对象上,完全不会修改main中创建的类实例的成员变量- 输入、输出逻辑分散在无关的成员函数里,没有和重载的
cin >>、cout <<操作绑定
修复方案
1. 补全友元运算符重载的实现
在类外编写两个重载函数的具体逻辑,把原本写在applyPercentage()里的输入逻辑挪到operator>>中,原本写在computeTotalAccountValue()里的输出逻辑挪到operator<<中:
// 输入运算符重载 istream& operator>>(istream& in, Section_401k& emp) { cout << "Internal Revenue Code: Section 401(k)\n"; cout << "Annual Salary ($): "; in >> emp.annual_salary; cout << "Annual Salary Increase (%): "; in >> emp.annual_salary_increase; emp.annual_salary_increase /= 100.0; cout << "Annual Rate of Return (%): "; in >> emp.annual_rate_of_return; emp.annual_rate_of_return /= 100.0; cout << "Current Age: "; in >> emp.current_age; cout << "Age of Retirement: "; in >> emp.age_of_retirement; cout << "Current 401k Balance ($): "; in >> emp.current_balance; cout << "Contribution to 401k (%): "; in >> emp.contribution; emp.contribution /= 100.0; cout << "Employer Match (%): "; in >> emp.employer_match; emp.employer_match /= 100.0; cout << "Employer Max Contribution (%): "; in >> emp.employer_max_contribution; emp.employer_max_contribution /= 100.0; // 输入完成后自动计算账户总值 emp.computeTotalAccountValue(); return in; } // 输出运算符重载 ostream& operator<<(ostream& out, const Section_401k& emp) { out << "\nYour 401(k) Summary\n"; out << "Annual Salary ($): " << emp.annual_salary << "\n"; out << "Annual Salary Increase (%): " << emp.annual_salary_increase << "\n"; out << "Annual Rate of Return (%): " << emp.annual_rate_of_return << "\n"; out << "Current Age: " << emp.current_age << "\n"; out << "Age of Retirement: " << emp.age_of_retirement << "\n"; out << "Current 401k Balance ($): " << emp.current_balance << "\n"; out << "Contribution to 401k (%): " << emp.contribution << "\n"; out << "Employer Match (%): " << emp.employer_match << "\n"; out << "Employer Max Contribution (%): " << emp.employer_max_contribution << "\n"; out << "Total Account Value at Age " << emp.age_of_retirement << ": $" << emp.totalAccountValue << "\n"; return out; }
2. 修复类成员函数的逻辑错误
- 同步删除类内
void applyPercentage();的声明,以及整个applyPercentage()函数的实现,所有输入逻辑已经移到operator>>中,不需要这个冗余函数 - 修改
computeTotalAccountValue(),直接操作当前类实例的成员,不要在函数内部新建临时对象:
void Section_401k::computeTotalAccountValue() { double rate = annual_rate_of_return; double CB = current_balance; int n = age_of_retirement - current_age; double YC = (annual_salary * contribution) / 12.0; double EC = YC * employer_match; totalAccountValue = (CB * pow((1 + (rate / 12.0)), 12 * n)) + ((YC + EC) * (pow((1 + (rate / 12.0)), 12 * n) - 1)) / (rate / 12.0) * (1 + (rate / 12.0)); }
3. 编译注意事项
使用g++编译时需要手动链接数学库,否则会抛出pow函数的链接错误,编译命令为:g++ your_code.cpp -o 401k_calc -lm
内容的提问来源于stack exchange,提问作者Matthim
相关产品推荐
相关产品推荐

