运算符<<过载"error: passing 'const...."
operator<< overloading "error: passing 'const...."
ofstream& operator<<(ostream &outStream, const EventClass &eventObject)
{
outStream << eventObject.getEventName() << " event at "
<< eventObject.getEventTime() << endl;
return(outStream);
}
我相信这个片段足以分析错误。
当我编译代码时,出现以下错误:
错误:将"const EventClass"作为"std::string EventClass::getEventName(("的"this"参数传递丢弃限定符 [-fpermissive]
outStream <<eventObject.getEventName(( <<" event at ">错误:将"const EventClass"作为"int EventClass::getEventTime(("的"this"参数传递丢弃限定符[-fpermissive]
错误:从
<<eventObject.getEventTime(( <<endl;类型"std::ostream {aka std::basic_ostream}"的表达式中初始化类型"std::ofstream&{aka std::basic_ofstream&}"的引用无效
返回(流(;
任何想法如何解决这些错误?
确保getEventName
和getEventTime
声明为 const
,如下所示:
std::string getEventName() const;
int getEventTime() const;
在EventClass
的声明和实施中.这告诉编译器这些方法不会以任何方式修改对象的字段。
此外,运算符的最后一行应该只是:return outStream;
编辑:std::ofstream
也与std::ostream
不同。一般来说,对于operator<<
,它需要定义为:
std::ostream& operator<<(std::ostream& os, const EventClass& eventObject) {
//blah
}
以包含任何流类型。
eventObject
是对const
对象的引用,因此它的 getEventName()
和 getEventTime()
方法也需要声明为 const
,以指定它们不修改调用它们的对象,例如:
std::string getEventName() const;
int getEventName() const;
此外,您的运算符被声明为返回 ofstream
,但它需要返回一个 ostream
以匹配输入:
ostream& operator<<(ostream &outStream, const EventClass &eventObject)