重载<<具有映射容器中的映射值的运算符

时间:2012-04-27 15:01:22

标签: c++ pointers reference map g++

我无法重载运算符<< ,以便在我的地图中使用映射值

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

我已尝试过这两种方法:

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; 
}

在我的节目中,我只需致电:

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

我也尝试过:

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

任何人都知道我可以更改以输出映射值的值而不是地址吗?

感谢任何帮助

1 个答案:

答案 0 :(得分:3)

不要将abs用作类型 - abscstdlib标头中声明的函数。您没有提供该类型的声明,因此此示例使用了一些虚构的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