我在一个抽象类的头文件中找到了这个函数:
virtual ostream & print( ostream & out ) const;
谁能告诉我这是什么函数以及如何在派生类中声明它? 据我所知,它似乎返回了对外流的引用。
如果我在没有任何内容的 cc 文件中实现它,我会得到一个编译器错误:
错误:预期构造函数、析构函数或“&”标记之前的类型转换
谁能告诉我如何使用它的简单实现?
最佳答案
您可能忘记包含 iostream
,这使得 ostream
可见。您还需要将其更改为 std::ostream
,因为 C++ 标准库名称位于命名空间 std
中。
Do not write
using namespace std;
in a header-file, ever!
如果你愿意,或者如果你为 friend 写了一个例子,把它放在实现文件中是可以的。因为任何包含该 header 的文件都会将所有标准库作为全局名称显示,这是一个巨大的困惑并且闻起来很臭。它突然增加了与其他全局名称或其他 using
命名的名称冲突的机会 - 我会完全避免使用指令(请参阅 Herb Sutter 的 Using me)。所以把代码改成这个
#include <iostream>
// let ScaryDream be the interface
class HereBeDragons : public ScaryDream {
...
// mentioning virtual in the derived class again is not
// strictly necessary, but is a good thing to do (documentary)
virtual std::ostream & print( std::ostream & out ) const;
...
};
并在执行文件(.cpp)中
#include "HereBeDragons.h"
// if you want, you could add "using namespace std;" here
std::ostream & HereBeDragons::print( std::ostream & out ) const {
return out << "flying animals" << std::endl;
}
关于c++ - 如何实现 'virtual ostream & print( ostream & out ) const;',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1069335/