Overload << operator with the displayed value in the map container

I have an overload operator << problem for use with the displayed value on my map:

map<string,abs*> _map;
// that my declaration, and I have filled it with keys/values

Ive tried both of them:

std::ostream& operator<<(std::ostream& os, abs*& ab) 
{ 
    std::cout << 12345 << std::endl; 
}

std::ostream& operator<<(std::ostream& os, abs* ab)
{ 
    std::cout << 12345 << std::endl; 
}

In my program, I just call:

std::cout << _map["key"] << std::endl; 
// trying to call overloaded operator for mapped value
// instead it always prints the address of the mapped value to screen

Ive also tried:

std::cout << *_map["key"] << std::endl; 
// trying to call overloaded operator for mapped value
// And that gives me a really long compile time error

Does anyone know what I can change to get this, to output the value of the displayed value instead of the address?

Any help is appreciated

+3
source share
1 answer

abs - abs - , cstdlib. , - abs:

#include <map>
#include <string>
#include <iostream>

struct Abs
{
    Abs(int n) : n_(n){}
    int n_;
};

std::ostream& operator<<(std::ostream& os, const Abs* p) 
{ 
    os << (*p).n_;
    return os;
}

int main(int argc, char** argv)
{
    std::map<std::string, Abs*> map_;
    Abs a1(1);
    Abs a2(2);

    map_["1"] = &Abs(1);
    map_["2"] = &Abs(2);
    std::cout << map_["1"] << ", " << map_["2"] << std::endl;
}

:

 1, 2
+3

All Articles