【发布时间】:2011-08-27 00:08:29
【问题描述】:
我一直在努力寻找答案,但似乎没有人遇到与我完全相同的问题。
我正在处理几个派生类。 ostream 操作符 例如:
基类 .h 文件
class Base
{
int FirstClassNumber;
//The declaration I'm currently working with, that a friend gave me
//I'm pretty sure my problem lies here.
public:
friend ostream& operator << (ostream& os, const Base &base)
{
base << os ;
return os;
}
virtual void operator << (ostream& os) const = 0;
};
Base.cpp 文件包括以下几行:
void Base::operator << (ostream& os)
{
os << FirstClassNumber;
}
然后我推导:(FirstDerived.h)
class FirstDerived : Public Base
{
int SecondClassNumber;
};
FirstDerived.cpp:
FirstDerived::operator << (ostream& os)
{
os <<
"The first Number is:
//This is the line that isn't working - someone else gave me this syntax
<< Base::operator<<
<< "The second number is"
<< SecondClassNumber;
}
那我要推导:
class SecondDerived: Public FirstDerived
{
int ThirdClassNumber;
};
第二个.cpp:
FirstDerived::operator << (ostream& os)
{
os <<
FirstDerived::operator<<
<< "The third number is "
<< ThirdClassNumber;
}
我认为问题很可能是程序一开始的声明,或者像Base::operator<< 这样的行。
另一种可能性是我没有在每个继承类的 .h 文件中重新声明它。我应该是,如果是,我应该使用什么语法?
有人建议我使用static_cast 方法,但我的教授(写作业的人,因此不会给我们太多帮助)说有更好的方法来做。有什么建议吗?
【问题讨论】:
-
“我认为问题很可能是......” - 您观察到什么症状?编译错误?线路,消息?还是不希望的运行时行为?如果是这样,你期望什么?
标签: c++ inheritance operator-overloading ostream