Link to home
Start Free TrialLog in
Avatar of seagu11
seagu11

asked on

operator<< overloading

I have two classes that I need to overload the stream operator << on. One works, the other doesn't, but I'm having trouble seeing why the latter doesn't work.

Here they are. I'm hoping someone can help me point out the difference.

/////////////////////////////////////////////////////////////////////////////
// this class overloads << just fine.
class Location {
public:
    Location(Country country, std::string& location_name);
    Country country() const { return myCountry; }
    const std::string& locationName() const { return myLocationName; }
    float longDistanceRateFromCanada() const;

private:
    Country myCountry;
    std::string myLocationName;
};

static std::ostream& operator<<(std::ostream& os, const Location& location) {
    os << location.locationName();
    return os;
}
////////////////////////////////////////////////////////////////
// this class does not

class PhoneNumber {
private:
    unsigned long myPhoneNumber;
public:
    PhoneNumber(unsigned long p) { myPhoneNumber = p; }
    int areaCode();
    unsigned long getNumber();
};

static std::ostream& operator<<(std::ostream& os, const PhoneNumber& pn) {
    os << pn.getNumber();
    return os;
}
///////////////////////////////////////////////////////////

Thanks for any help you can provide.




Avatar of AlexFM
AlexFM

What doesn't work exactly? Not compiled, not linked, doesn't print anything, prints junk etc.
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of seagu11

ASKER

I apologize for not including the error. I totally meant to.

In file included from PhoneNumber.cpp:1:
PhoneNumber.h: In function `class ostream & operator <<(ostream &, const PhoneNumber &)':
PhoneNumber.h:16: passing `const PhoneNumber' as `this' argument of `long unsigned int PhoneNumber::getNumber()' discards qualifiers
*** Error code 1
Avatar of seagu11

ASKER

Thanks AlexFM. Making the getNumber() function const did the trick.
it's implementation was simply

unsigned long PhoneNumber::getNumber() const{
    return myPhoneNumber;
}

Now I need to find out *why* that worked so I don't do it again.
static std::ostream& operator<<(std::ostream& os, const PhoneNumber& pn)

This declares pn as const, so you cannot call non-const PhoneNumber members. Marking getNumber const (and it is really const because it doesn't change class members) makes C++ compiler happy.