Reputation: 431
I'm stuck on an error from so long now, the following, I'm learning and I think I don't understand the error.
droid.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Droid&)’:
droid.cpp:94:30: error: passing ‘const Droid’ as ‘this’ argument of ‘std::string
Droid::getId()’ discards qualifiers
[-fpermissive]
the line 94:
std::ostream& operator<<(std::ostream &os, Droid const & a)
os << "Droid '" << a.getId() << "', " << *a.getStatus() << ", " << a.getEnergy() << std::endl;
and hearders :
std::string getId();
I have the same error for the 3 calls in "operator<<", a.getId, a.getStatus, a.getEnergy.
Can someone could explain to me what the compiler is saying?
Upvotes: 4
Views: 12213
Reputation: 62093
You need std::string getId() const;
. Otherwise, the compiler thinks getId()
might change the instance, which you can't do on a const Droid&
. Same thing for getStatus()
and getEnergy()
.
Upvotes: 3
Reputation: 227468
You need to make that method const
so it can be called on a const
instance or via a const
reference:
std::string getId() const;
^^^^^
The same would apply to all Droid
methods called in std::ostream& operator<<(std::ostream &os, Droid const & a)
.
You will also need to add the const
in the method's definition.
Upvotes: 10