4
votes

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!

2
This works fine as long as you are creating the object NumExpr by using proper constructor. - Alok Save
It compiles: ideone.com/aZTvQ . Can you show us the calling code? - Naveen
interesting! I haven't added the calling code for the function yet. Its just freshly made and having problems without me having to call it. By the way I am using the g++ command on linux if it helps any. @Naveen Hmm, that looks like how I would instantiate the class, not sure why its not working out on my side. - Jason Hu

2 Answers

5
votes

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.

0
votes

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?