gpt4 book ai didi

c++ - "Undefined Symbols"但函数已定义和声明,没有拼写错误

转载 作者:行者123 更新时间:2023-11-30 01:19:13 25 4
gpt4 key购买 nike

我遇到了这个奇怪的问题 - 我定义和声明了函数,没有拼写错误,没有外部库,没有命名空间失败,没有模板,没有提到任何其他线程 - 但我仍然得到函数调用的“ undefined symbol ” .

我有以下代码:

在一个 .cpp 文件中:

string print(const FanBookPost& post) {
std::stringstream ss;
// notice! post.getOwner.getId! owner needs to be fan
ss << post.getOwner().getId() << ": " << post.getContent() << "(" << post.getNumLikes()
<< " likes)";
return ss.str();
}

该文件包括 FanBookPost.h。

然后我在 FanBookPost.h 中有:

class FanBookPost {

private:

Fan owner;
std::string content;
int numOfLikes;
int seqNum;

public:

// constructors


int getNumLikes();
std::string getContent();
Fan getOwner();

int getNumLikes() const;
std::string getContent() const;
Fan getOwner() const;

};

如您所见,我准备了 const 和常规版本。在第一个 .cpp 文件中,“post”函数获取的是 const。

我在 FanBookPost.cpp 中实现了这些功能:

class FanBookPost {

private:

Fan owner;
std::string content;
int numOfLikes;
int seqNum;

public:

//constructors

int getNumLikes() {
// code
}

std::string getContent() {
// code
}

Fan getOwner() {
// code
}


int getNumLikes() const {
// code
}

std::string getContent() const {
// code

}

Fan getOwner() const {
// code
}

};

我尝试用谷歌搜索答案并搜索 stackoverflow 线程,但正如我所说,没有发现任何明显的问题。请帮我解决这个“ undefined symbol ”问题,因为它已经让我发疯了。

最佳答案

i have those functions implemented here, in FanBookPost.cpp

不,你不知道!您已经重新定义了类,而不仅仅是定义函数。这打破了单一定义规则,所以各种各样的事情都可能出错。特别是,这些函数是内联的,因此它们对其他源文件不可用;因此你的错误。

源文件应该看起来更像

#include "FanBookPost.h" // include the class definition

// Define the member functions
int FanBookPost::getNumLikes() {
// code
}

// and so on

或者,您可以在 header 中的类定义中定义函数,或者在类定义之后使用 inline 说明符;如果它们非常小,这可能是合适的,因为它为编译器提供了更好的优化机会。但无论哪种情况,您都只能在 header 中定义一次类。

关于c++ - "Undefined Symbols"但函数已定义和声明,没有拼写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21138434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com