对在 header 中声明并在 cpp 文件中实现的函数的未定义引用

undefined reference to function declared in header and implemented in cpp file

我正在编写一些使用两个 cpp 文件(Main.cpp 和 CarbStore.cpp)和一个 header(CarbStore.h)的基本 C++ 代码。在我的 header 中,我声明了一个稍后在 CarbStore.cpp 中实现的函数。当我从我的 Main.cpp 调用该函数时,它给我错误:

Main.cpp:17: undefined reference to `CarbStore::CalcCarbs(unsigned char, unsigned char, unsigned char, float, unsigned int, std::__cxx11::basic_string, std::allocator >) const'

我的文件包含以下代码:

Main.cpp

#include <iostream>
#include <cstdint>
#include <cmath>
#include <ctime>

#include "CarbStore.h"


void CarbCalculator()
{
    CarbStore carb;
    carb.CalcCarbs(10, 11, 12, 0.1, 100, "test");
}

int main(int,char *[])
{
    CarbCalculator();

    std::cout << "Press enter to exit." << std::endl;
    std::cin.get();
}

CarbStore.cpp

#include "CarbStore.h"
#include <iostream>

void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
    //use values at later state
    return;
}

CarbStore.h

#ifndef CARBSTORE_H
#define CARBSTORE_H
#include <vector>

class CarbStore
{
public:
    void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer) const;
};



#endif

如评论中所述,以下内容

void CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
    //use values at later state
    return;
}

没有实现 CarbStore 的成员函数 CalcCarbs,而是声明并定义了一个名为 CalcCarbs 的新自由函数。要实现成员函数,您需要告诉编译器函数定义应该属于哪个class。这是通过在函数名称前附加 class 名称和双冒号来完成的:

void CarbStore::CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer)
{
    //use values at later state
    return;
}

签名也必须匹配。在 CarbStore 中你声明了函数 const,但你在实现中没有这样做。要更正它:

void CarbStore::CalcCarbs(unsigned char r, unsigned char b, unsigned char g, float bounciness, unsigned int price, std::string manufacturer) const
{
    //use values at later state
    return;
}

然而,你不太可能真的想要一个空 return 的 const 成员函数,因为这样的函数只能通过修改全局变量或进行 IO 来产生持久效果。

此外,但与此特定错误消息无关:

  1. CarbStore 中您使用的是 std::string,因此您需要 #include<string>。另一方面,我没有在其中看到任何 std::vector,因此 #include<vector> 似乎是不必要的(除了 Main.cpp 中的 iostream 之外的所有其他内容也是如此)。
  2. 函数体末尾的 return; 对于 void 函数也是没有意义的。
  3. 如果main不使用命令行参数,你也可以给它签名int main().