"Undefined Symbols"但定义和声明了函数,没有错别字
"Undefined Symbols" but functions are defined and declared, no typos
我遇到了这个奇怪的问题 - 我定义和声明了函数,没有拼写错误,没有外部库,没有命名空间失败,没有模板,没有其他线程提及 - 但我仍然得到函数调用的"未定义符号"。
我有以下代码:
在一个.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
}
};
我试图谷歌答案并搜索堆栈溢出线程,但正如我所说,找不到任何明显的问题。 请帮我解决这个"未定义的符号"问题,因为它已经让我发疯了。
我在FanBookPost中实现了这些功能.cpp
不,你没有!您已经重新定义了类,而不仅仅是定义函数。这违反了一个定义规则,所以所有的事情都可能出错。特别是,这些函数是内联的,因此它们不适用于其他源文件;因此你的错误。
源文件应该看起来更像
#include "FanBookPost.h" // include the class definition
// Define the member functions
int FanBookPost::getNumLikes() {
// code
}
// and so on
或者,您可以在标头中的类定义中定义函数,或者在类定义之后使用inline
说明符定义函数;如果它们非常小,这可能是合适的,因为它为编译器提供了更好的优化机会。但无论哪种情况,您都只能在标头中定义一次类。
由于您使用const
引用FanBookPost
,因此您需要getOwner()
才能const
:
Fan getOwner() const;
(无论如何,如果它是一个简单的getter),它应该是)。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- "Undefined Symbols"但定义和声明了函数,没有错别字