class 中的 ostream 没有类型

ostream in class does not have a type

刚接触 C++,我有一个小问题。

编译后
g++ *.cpp -o output

我收到此错误:

error: 'ostream' in 'class Dollar' does not name a type

这是我的三个文件:

main.cpp

#include <iostream>
#include "Currency.h"
#include "Dollar.h"

using namespace std;

int main(void) {
    Currency *cp = new Dollar;

    // I want this to print "printed in Dollar in overloaded << operator"
    cout << cp;
    return 0;
}

Dollar.cpp

#include <iostream>
#include "Dollar.h"

using namespace std;

void Dollar::show() {
    cout << "printed in Dollar";
}

ostream & operator << (ostream &out, const Dollar &d) {
    out << "printed in Dollar in overloaded << operator";
}

Dollar.h

#include "Currency.h"

#ifndef DOLLAR_H
#define DOLLAR_H

class Dollar: public Currency {
    public:
        void show();
};

ostream & operator << (ostream &out, const Dollar &d);

#endif

感谢您的宝贵时间,一切都会有所帮助!

您需要 #include <iostream> 在 Dollar.h 内,以便您的 std::ostream & operator 由编译器解析。

您的代码中有很多错误。

  1. 您经常使用 using namespace stdThis is a bad practice。特别是,这导致了您遇到的错误:Dollar.h 中没有 using namespace std,因此编译器不知道 ostream 是什么意思。要么把 using namespace std 也放在 Dollar.h 中,要么最好停止使用它并直接指定 std 命名空间,如 std::ostream.
  2. 您在 header 中使用了 std::ostream,但是您没有在其中包含相应的标准库 header <ostream><ostream> 包含std::ostream class 的定义;完整的 I/O 库包含 <iostream>)。一个非常好的做法是将 header 的所有依赖项包含在 header 本身中,这样它就是 self-contained 并且可以安全地包含在任何地方。
  3. 您正在实现带有签名 std::ostream & operator << (std::ostream &, Dollar const &) 的流输出运算符,这是完全有效的。但是,您调用它是为了 指针 以键入 Dollar。你应该用 object 本身而不是指针来调用它,所以你应该取消引用指针:std::cout << *cp;.
  4. 您为 Dollar class 实现了输出运算符,但将其用于 Currency 类型的变量:这将不起作用。有一种方法可以做到这一点——出于这个确切的原因,确实存在虚拟方法。但是,在这种情况下,运算符是一个自由函数,因此它不能是虚拟的。因此,您可能应该向 Currency class 添加一个虚拟 print 方法,在 Dollar 中实现它,并从输出运算符调用它:

    #include <iostream>
    
    class Currency {
    public:
        virtual void print (std::ostream &) const = 0;
    };
    
    class Dollar : public Currency {
        void print (std::ostream & out) const override {
            out << "A dollar";
        }
    };
    
    std::ostream & operator << (std::ostream & out, Currency const & c) {
        c.print(out);
        return out;
    }
    
    int main(/* void is redundant here */) {
        Currency *cp = new Dollar;
        std::cout << *cp;
        // return 0 is redundant in main
    }