将“const Link”作为“std::string GetAttribute(std::string)”的“this

passing ‘const Link’ as ‘this’ argument of ‘std::string GetAttribute(std::string)’ discards qualifiers

本文关键字:string std this GetAttribute Link const 作为      更新时间:2023-10-16

我在使用NS-3 API的某些部分时遇到奇怪的错误。这是我的错误消息:

error: passing ‘const ns3::TopologyReader::Link’ as ‘this’ argument of ‘std::string ns3::TopologyReader::Link::GetAttribute(std::string)’ discards qualifiers

这是导致问题的代码:

TopologyReader::ConstLinksIterator iter;
int num = 0;
for (iter = topologyReader->LinksBegin (); iter != topologyReader->LinksEnd(); iter++, num++)
  {
    std::istringstream fromName(iter->GetFromNodeName ());
    std::istringstream toName (iter->GetToNodeName ());
    iter->GetToNodeName();
    std::string w = "Weight";
    std::string weightAttr = (iter)->GetAttribute(w); // <- error
    /* snip */
  }

我认为这可能与以下事实有关:根据 TopologyReader::Link 的文档,GetAttribute(std::string)不是const函数,而其他函数、GetFromNodeName(void)GetToNodeName(void) 被声明为const函数。但是,我不确定如何解决此问题。

编辑:函数签名如下所示(来自链接的文档(:

std::string ns3::TopologyReader::Link::GetFromNodeName (void) const
std::string ns3::TopologyReader::Link::GetToNodeName (void) const
std::string ns3::TopologyReader::Link::GetAttribute (std::string name)  

你的分析是正确的。显而易见的解决方法是使GetAttribute成为一个 const 函数。它的名字表明它应该是常量。但是,您可能无权更改该代码。

另一种方法是找到某种方法来获取非 const 对象来调用函数。也许您可以将iter声明为LinksIterator而不是ConstLinksIterator.

作为最后的手段,您可以尝试使用 const_cast 告诉编译器在假定的 const 对象上调用非 const 方法确实是安全的。