类中的ostream没有类型

时间:2018-01-16 21:35:24

标签: c++ inheritance header-files ostream istream

刚进入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

感谢您的时间,一切都有帮助!

2 个答案:

答案 0 :(得分:6)

代码中有许多错误。

  1. 您大量使用using namespace stdThis is a bad practice。特别是,这导致您遇到的错误:您在using namespace std中没有Dollar.h,因此编译器不知道ostream的含义。也可以将using namespace std放入Dollar.h,或者更好地停止使用它并直接指定std命名空间,如std::ostream
  2. 您在标题中使用std::ostream,但未在其中包含相应的标准库标题<ostream><ostream>包含std::ostream类的定义;对于完整的I / O库,包括<iostream>)。一个非常好的做法是在标题本身中包含标题的所有依赖项,以便它是自包含的并且可以安全地包含在任何地方。
  3. 您正在实现一个带有签名std::ostream & operator << (std::ostream &, Dollar const &)的流输出运算符,该运算符完全有效。但是,您可以将其命名为指针以键入Dollar。您应该使用对象本身而不是指针来调用它,因此您应该取消引用指针:std::cout << *cp;
  4. 您为Dollar类实现了输出运算符,但将其用于Currency类型的变量:这不会起作用。有一种方法可以做到这一点 - 确实存在虚拟方法。但是,在这种情况下,操作员是自由功能,因此它不能是虚拟的。因此,您可能应该向print类添加虚拟Currency方法,在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
    }
    

答案 1 :(得分:0)

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