【问题标题】:Overloading << operator with mapped value in a map container在地图容器中使用映射值重载 << 运算符
【发布时间】:2012-05-08 08:14:00
【问题描述】:

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

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

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

感谢任何帮助

【问题讨论】:

  • 你能发布一个完整的小样本吗?
  • 您发布的代码可以正常工作。问题在于您没有发布的代码。请将您的实际程序简化为演示问题的最小完整示例。您很可能会自己发现问题。如果没有,请在您的问题中发布完整的小示例。见sscce.org
  • 附言。 works for me.
  • 你没有从你的运营商那里返回一个 ostream
  • 是否有任何命名空间在起作用? map&lt;string,abs*&gt; _map; 声明、operator&lt;&lt; 声明和使用它们的代码在哪个命名空间中?

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


【解决方案1】:

不要使用 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

【讨论】:

  • 其实这个类叫Abstract,你觉得有问题吗?
  • 不,这个名字很好。 map_["key"] 在您的情况下返回对 Abstract* 类型的值的引用。 ostream::operator&lt;&lt; 对内置类型(如 intfloat...和指针)进行了重载,这就是为什么您在第一次调用中打印了该对象的地址。如果要显示类Abstract 的某个数据成员的值,则需要为Abstract* 类型重载operator&lt;&lt;(参见我上面的示例),然后将map_["key"] 传递给它或重载它输入Abstract(这实际上是一种常见的做法),然后将*(map_["key"]) 传递给它。
  • 感谢您的帮助。我发现问题是我的 Abstract 类没有将 operator
  • 谢谢布莱恩。是的,我在上面的示例中使用了 struct,并且默认情况下所有 struct 成员都是 public,因此 operator&lt;&lt; 可以访问其成员而不是其 friend。上课是另一回事......但你现在知道了:)
猜你喜欢
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2014-11-07
  • 2010-09-13
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多