我在一个抽象类的头文件中找到了这个函数:
virtual ostream & print( ostream & out ) const;谁能告诉我这是什么类型的函数,以及如何在派生类中声明它?据我所知,它看起来像是返回了一个对外流的引用。
如果我在没有任何内容的cc文件中实现它,我会得到一个编译器错误:
error: expected constructor, destructor, or type conversion before ‘&’ token
有人能给我演示一下如何使用它的简单实现吗?
发布于 2009-07-01 14:18:05
一些实现:
ostream& ClassA::print( ostream& out) const
{
out << myMember1 << myMember2;
return out;
}返回相同的ostream允许像这样的组合
a.print( myStream) << someOtherVariables;然而,以这种方式使用它仍然很奇怪。
关于错误,ostream是std名称空间的一部分,而不是全局名称空间的一部分,也不是您引用的类所属的名称空间的一部分。
发布于 2009-07-01 14:19:34
您可能忘记了包含使ostream可见的iostream。您还需要将其更改为std::ostream,因为C++标准库名称在名称空间std中。
Do
using namespace std;in a header-file,永不!
如果你愿意,或者如果你为一个朋友写了一个例子,你可以把它放到实现文件中。因为任何包含该头文件的文件都会将所有标准库都显示为全局名称,这是一个巨大的混乱,而且有很多异味。它突然增加了与其他全局名称或其他using'ed名称发生名称冲突的可能性--我会完全避免使用指令(参见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;
}发布于 2009-07-01 14:15:53
#include <iostream>
using namespace std;
struct A {
virtual ostream & print( ostream & out ) const {
return out << "A";
}
};将打印函数设为虚函数是很常见的,因为通常用于流输出的<<操作符无法设为虚函数(因为它不是成员函数)。
https://stackoverflow.com/questions/1069335
复制相似问题