标识符“ostream"是未定义的错误

2021-12-31 00:00:00 operators compiler-errors c++ ostream

我需要实现一个支持运算符<<的数字类为输出.我有一个错误:标识符ostream"未定义"出于某种原因,尽管我包括并尝试了

i need to implement a number class that support operator << for output. i have an error: "identifier "ostream" is undefined" from some reason eventhough i included and try also

这里是头文件:

数字.h

#ifndef NUMBER_H
#define NUMBER_H
#include <iostream>
class Number{
public:
//an output method (for all type inheritance from number):
virtual void show()=0;

//an output operator:
friend ostream& operator << (ostream &os, const Number &f);


};

#endif

为什么编译器不识别友元函数中的ostream?

why the compiler isnt recognize ostream in the friend function?

推荐答案

您需要使用类所在的命名空间的名称来完全限定名称 ostream:

You need to fully qualify the name ostream with the name of the namespace that class lives in:

    std::ostream
//  ^^^^^

所以你的操作符声明应该变成:

So your operator declaration should become:

friend std::ostream& operator << (std::ostream &os, const Number &f);
//     ^^^^^                      ^^^^^

或者,您可以在非限定名称 ostream 出现之前使用 using 声明:

Alternatively, you could have a using declaration before the unqualified name ostream appears:

using std::ostream;

这将允许您在没有完全限定的情况下编写 ostream 名称,就像在您当前版本的程序中一样.

This would allow you to write the ostream name without full qualification, as in your current version of the program.

相关文章