"Undefined Symbols"但定义和声明了函数,没有错别字

"Undefined Symbols" but functions are defined and declared, no typos

本文关键字:函数 错别字 声明 Undefined Symbols 定义      更新时间:2023-10-16

我遇到了这个奇怪的问题 - 我定义和声明了函数,没有拼写错误,没有外部库,没有命名空间失败,没有模板,没有其他线程提及 - 但我仍然得到函数调用的"未定义符号"。

我有以下代码:

在一个.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),它应该是)。