运算符<<过载"error: passing 'const...."

operator<< overloading "error: passing 'const...."

本文关键字:lt const passing error 过载 运算符      更新时间:2023-10-16
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&}"的引用无效
返回(流(;

任何想法如何解决这些错误?

您需要

确保getEventNamegetEventTime声明为 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)