C++ Stream Extraction Operator>> 已声明但未定义,即使已定义

C++ Stream Extraction Operator>> Declared But Not Defined Even Though It Is Defined

所以我在 stockType.h

#include <iostream>
class stockType {
public:
    //...
    static friend std::ostream& operator<<(std::ostream& out, const stockType& stock);
    static friend std::istream& operator>>(std::istream& in, stockType& stock);
private:
    //...
}

并在 stockType.cpp

std::ostream& operator<<(std::ostream& out, const stockType& stock) {
    //...
}

std::istream& operator>>(std::istream& in, stockType& stock) {
    //...
}

我对 operator<< 没有任何问题,但编译器给我一个致命错误“static function 'std::istream &operator >>(std::istream &,stockType &)' declared but not defined”,它说它发生在 main.cpp 第 32 行,但只有 31 行在 main.cpp.

将自由函数(friend 函数不是 class 中的方法)标记为 static 表示它将在当前翻译单元中定义。将 static 函数放在 header 中意味着包括 header 在内的所有翻译单元都必须对该函数有自己的定义。您应该从声明中删除 static(clang 和 gcc 实际上拒绝您的代码为 invalid)。

请注意,这与 static 成员函数不同,后者表示该方法在 class 中可用,而不是在实例中可用。这是 c++ 使用相同关键字在不同上下文中表示不同事物的众多令人困惑的地方之一。