【问题标题】:passing string by reference wrong c++通过引用传递字符串错误的C++
【发布时间】:2023-03-27 03:05:02
【问题描述】:

我正在编写一个简单的类并得到一些错误。头文件如下图:

//
//  temp.h
//

#ifndef _TEMP_h
#define _TEMP_h

#include <string>
using namespace std;

class GameEntry {
public:
  GameEntry(const string &n="", int s=0);
  string getName();
  int getScore();
private:
  string name;
  int score;
};

#endif

方法文件如下图:

// temp.cpp

#include "temp.h"
#include <string>
using namespace std;

GameEntry::GameEntry(const string &n, int s):name(n),score(s) {}

string GameEntry::getName() { return name; }

int GameEntry::getScore() { return score; }

主文件如下图:

#include <iostream>
#include <string>
#include "temp.h"
using namespace std;

int main() {
  string str1 = "Kenny";
  int k = 10;
  GameEntry G1(str1,k);

  return 0;
}

我收到这样的错误:

Undefined symbols for architecture x86_64:
  "GameEntry::GameEntry(std::__1::basic_string<char, std::__1::char_traits<char>,
                        std::__1::allocator<char> > const&, int)", referenced from:
      _main in main1-272965.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

谁能告诉我怎么了?非常感谢。

【问题讨论】:

  • 您是如何调用编译器和链接器的?好像你忘了链接temp.o
  • 你是怎么编译的?什么是命令行?
  • 我只是简单地尝试“c++ main.cpp”,它通常对我有用。
  • 您需要将temp.cpp 编译成一个目标文件(temp.o) 并将其与main.cpp 链接。试试g++ -c temp.cppg++ main.cpp temp.o。这是对以下答案中的更正的补充。
  • 是的,这解决了问题。不过,我不太明白。我认为对于类似的实现,甚至更大的类,我通常只在 main 中包含头文件,并且只使用“c++ main.cpp”。你能提供更多这样做的理由吗?

标签: c++ string class reference


【解决方案1】:

你不能把默认参数放在定义中:

GameEntry::GameEntry(const string &n, int s):name(n),score(s) {}

编辑:实际上你可以把它放在定义中,但你不能把它放在定义和声明中。更多信息可以在这个问题中找到:Where to put default parameter value in C++?

【讨论】:

  • 你的意思是在类文件中?我取出了默认值,但错误仍然存​​在。
  • .cpp文件中的定义。
  • 你只需要修改头文件就可以了。 @肯尼
  • 其实在书中,header中有默认值,class文件中没有默认值。我不清楚原因。
【解决方案2】:

除了纠正默认参数的问题,正如 clcto 和 G. Samaras 所指出的,您需要将 temp.cpp 编译为目标文件 (temp.o) 并将其与 main.cpp 链接。试试这个:

g++ -c temp.cpp

g++ main.cpp temp.o

在目标文件中找到缺少的符号,如果您没有显式编译 temp.cpp,则不会创建该符号。我认为您可能记错了过去的有效方法。

【讨论】:

  • 感谢所有建议。至于最后一句话,虽然我不是编译器专家,但不太可能。介意测试这个小代码。我记得它是通过“c++ main.cpp”工作的。 (在“rsmas.miami.edu/personal/wenliang.zhao/Software.htm”下载“sudoku.zip”
  • 如果我没有达到每日投票上限,我一定会投票给你,太好了!
【解决方案3】:

您不能在 .h 和 .cpp 文件中都有默认值。

将头文件中的原型改成这样:

GameEntry(const string &n, int s);

你很高兴。

在 main.cpp 中,您在这里错过了一个分号:int k = 10


一个有趣的链接:Where to put default parameter value in C++?

长话短说,由你决定。

如果它在头文件中,它有助于文档,如果它在源文件中,它实际上有助于阅读代码而不只是使用它的读者。

【讨论】:

    猜你喜欢
    • 2014-08-11
    • 2017-07-25
    • 2016-07-05
    • 2018-09-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2015-04-08
    相关资源
    最近更新 更多