【问题标题】:Undefined Reference error when passing String as a parameter将字符串作为参数传递时出现未定义的引用错误
【发布时间】:2021-12-31 21:26:23
【问题描述】:

我有一个 cpp 文件,它在 ABC 类中具有以下原型:

    # include relevant header    
    void ABC::get_strikes(int atm_f, int exp, std::string index)
    {
        int sum =5;
    }

函数在对应的hpp文件中声明:

#pragma once
#include <vector>

class ABC
{
    public:
    void get_strikes(int atm_f,int exp, std::string index);
}

我创建对象文件并使用ABC类的obj对象调用这个函数:

obj.get_strikes(3, 2, "Hello World");

这会导致未定义的引用错误:

undefined reference to `ABC::get_strikes(int, int, std::string)'

ABC 类中的所有其他功能都可以正确识别。 请注意,删除字符串作为参数而保留其他两个可以解决问题。 那么这是与字符串传递方式有关的问题吗?

【问题讨论】:

  • 应该可以,请提供minimal reproducible example
  • 如果问题是您没有在需要的地方#include &lt;string&gt;,您会看到多条错误消息。首先,编译器会发出一条或多条错误消息,告诉您不存在string(或std::string)这样的类型。您报告的“未定义”引用是在链接器之后发出的。所以你在这里提供了不完整的信息——发出的第一条错误消息通常是找出问题原因最重要的。而且您只提到了您看到的最后一条错误消息。
  • 您好,感谢您的回复,但这是唯一的错误消息。
  • @MrOmnipotent 你能检查我的回答是否解决了你的问题。尝试从我的答案中复制/粘贴文件,看看它是否可以编译。
  • @MrOmnipotent 在这种情况下,我们需要minimal reproducible example。它可能包含 3 个文件(ABC 的头文件和源文件)和一个包含 main 的源文件。您用来编译它的命令也会有所帮助。

标签: c++ string undefined


【解决方案1】:

您可能没有正确编译源文件。在这种情况下,如果您使用的是 ubuntu 和 gcc,那么您可以使用以下命令编译以下给定程序:

g++ main.cpp myfile.cpp -o program

我还注意到,在您的 cpp 文件中,您没有包含相应的标题。

所以不要忘记在 cpp 文件中包含相应的头文件,就像我在下面给出的程序中所做的那样,其输出可以看到 here

myfile.h

#pragma once
#include <vector>
#include <string>//added this
class ABC
{
    public:
    void get_strikes(int atm_f,int exp, std::string index);
};

myfile.cpp

#include "myfile.h"//added this

void ABC::get_strikes(int atm_f, int exp, std::string index)
{
    int sum =5;
  
}

ma​​in.cpp


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

int main()
{
  ABC obj;
  obj.get_strikes(3, 2, "Hello World");


    return 0;
}

【讨论】:

  • 嘿,谢谢您的回复,我这样做了,但无济于事。它仍然给我一个未定义的参考错误。我已经在cpp文件中包含了标题,我忘了在这里添加。
  • @MrOmnipotent 您使用的是哪个编译器?你用什么命令来编译你的程序?
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 2020-03-16
  • 1970-01-01
  • 2021-10-19
  • 1970-01-01
  • 2013-05-06
  • 2013-09-04
  • 1970-01-01
相关资源
最近更新 更多