C++:未定义的函数引用错误

C++: Undefined reference to function error

所以我有一个程序,其目的是使用重载函数计算医疗费用总额。但是当我尝试调用 if/else 语句块内的函数时出现问题。

在我编译它之前,确实没有指示器让我知道存在问题并且我被卡住了,我希望得到一些帮助。这是我得到的完整错误消息:In function main': main.cpp:(.text+0x14d): undefined reference to bill(float, float)' main.cpp:(.text+0x25b): 未定义引用`bill(float, float, float)' clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) 编译器退出状态 1

代码如下:

#include <iostream>
#include <iomanip>
using namespace std;

float choice, service_charge, test_charge, medicine_charge;

float bill(float, float);
float bill(float, float, float);

int main()
{
  
  cout << "Please input 1 if you are a member of"
    << " the dental plan" << ", Input any other number if you are not: " << endl;
  cin >> choice;

  if (choice == 1)
  {
    cout << "Please input the service charge: " << endl;
    cin >> service_charge;

    cout << "Please input the test charge: " << endl;
    cin >> test_charge;

    bill(service_charge, test_charge);
  }
  else
  {
    cout << "Please input the service charge: " << endl;
    cin >> service_charge;

    cout << "Please input the test charges: " << endl;
    cin >> test_charge; 

    cout << "Please input the medicine charges: " << endl;
    cin >> medicine_charge;

    bill(service_charge, test_charge, medicine_charge);
  }
  
  return 0;
}

float bill(float &refservice, float &reftest)
{
  cout << "The total bill is: $" << endl;
  return refservice + reftest;
}

float bill(float &refservice, float &reftest, float &refmed)
{
  cout << "The total bill is: $" << endl;
  return refservice + reftest + refmed;
}

原型的签名 float bill(float, float); 不等同于实际函数定义的签名 float bill(float &refservice, float &reftest)。您的其他原型和功能也有同样的问题。因此,编译器无法识别您已经定义了该函数。您必须更改原型的签名以匹配。在这种情况下,您的原型将如下所示:

float bill(float&, float&);
float bill(float&, float&, float&);

需要注意的一件事是,不清楚为什么必须通过引用传递这些浮点数,因为您没有以任何方式修改它们。