Reputation: 1267
I'm trying to overload the << operator for a class to emulate toString() in Java. I have a NumExpr
class, and has private variable number
that I want to output. so here they are:
NumExpr::NumExpr( string n ) {
number = atoi( n.c_str() );
}
string NumExpr::name() {
return "num";
}
ostream & operator<<(ostream &s, const NumExpr &num) {
s << num.number;
return s;
}
I made it a friend function so it can access the private variable
class NumExpr : public Expr {
public:
NumExpr( string v );
string name();
private:
int number;
friend ostream& operator<<(ostream &s, const NumExpr &num);
};
However I'm getting this error
./ast/Expr.cpp: In function ?std::ostream& operator<<(std::ostream&, const NumExpr&)?: ./ast/Expr.cpp:50: error: no match for ?operator<NumExpr::number? ./ast/Expr.cpp:49: note: candidates are: std::ostream& operator<<(std::ostream&, const NumExpr&)
I have searched for this error, people seem to be having the same problems but mine seems to look like the solutions people are giving out. Is there something fundamentally wrong that I'm doing or is there some syntax shenanigans that I'm not aware of?
Thanks for the help!
Upvotes: 4
Views: 375
Reputation: 206518
Okay here it is, little bit of playing around I can reproduce your problem:
The problem is that You forgot to include iostream header file.
Add:
#include<iostream>
and it should just work fine :)
EDIT:
As @James Kanze correctly suggests in comments, it is sufficient to include
#include<istream>
because you don't need everything from the iostream
really.
The downside of including iostream
inside of istream
is little increase in compilation time.
Upvotes: 6
Reputation: 33864
On this page:
http://www.cplusplus.com/forum/beginner/13164/
It says to have the friend function like this:
friend std::ostream& operator<< (std::ostream&, const NumExpr&); <-
so no variable decleration. just
const NumExpr
any help?
Upvotes: 0