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 に答える