1
votes
ofstream& operator<<(ostream &outStream, const EventClass &eventObject)
{
  outStream << eventObject.getEventName() << " event at "
    << eventObject.getEventTime() << endl;

  return(outStream);
}

I believe this snippet is sufficient to analyze the error.

When I compile my code I get the following errors:

error: passing ‘const EventClass’ as ‘this’ argument of ‘std::string EventClass::getEventName()’ discards qualifiers [-fpermissive]
outStream << eventObject.getEventName() << " event at "

error: passing ‘const EventClass’ as ‘this’ argument of ‘int EventClass::getEventTime()’ discards qualifiers [-fpermissive]
<< eventObject.getEventTime() << endl;

error: invalid initialization of reference of type ‘std::ofstream& {aka std::basic_ofstream&}’ from expression of type ‘std::ostream {aka std::basic_ostream}’
return(outStream);

Any ideas how to solve these errors?

2
Is the getEventName method marked as const?The Dark
No, it is not. Does it have to be const to solve the issue?roulette01
Yes, it has to be const to solve the problem.kfsone
Thanks that worked. What about the last error? it doesn't like my return statement.roulette01

2 Answers

3
votes

You need to make sure getEventName and getEventTime are declared as const, as follows:

std::string getEventName() const;
int getEventTime() const;

in the declaration and implementation of EventClass. This tells the compiler that these methods will not modify the fields of the object in any way.

Also, the last line of the operator should simply be: return outStream;

Edit: also std::ofstream is not the same as std::ostream. Generally, for operator<<, it needs to be defined as:

std::ostream& operator<<(std::ostream& os, const EventClass& eventObject) { 
    //blah 
}

to encompass any stream type.

0
votes

eventObject is a reference to a const object, so its getEventName() and getEventTime() methods need to be declared as const as well, to specify that they don't modify the object they are called on, eg:

std::string getEventName() const;
int getEventName() const;

Also, your operator is declared as returning an ofstream, but it needs to return an ostream instead, to match the input:

ostream& operator<<(ostream &outStream, const EventClass &eventObject)