首页 > 解决方案 > C ++:对函数错误的未定义引用

问题描述

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

在我编译它之前,真的没有任何指标可以让我知道有问题并且我被卡住了,我会很感激一些帮助。这是我得到的完整错误消息: In function main': main.cpp:(.text+0x14d): undefined reference to bill(float, float)' main.cpp:(.text+0x25b): undefined reference to `bill(float, float, float)' clang: error: linker command failed with退出代码 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;
}

标签: c++functionreference

解决方案


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

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

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


推荐阅读