3

我在重载 operator<<以与我的地图中的映射值一起使用时遇到问题:

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

任何人都知道我可以改变什么来让它输出映射值的值,而不是地址?

任何帮助表示赞赏

4

1 回答 1

3

不要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
于 2012-04-27T15:20:33.200 回答