gpt4 book ai didi

c++ - 传递 ‘const Link’ 作为 ‘this’ 的 ‘std::string GetAttribute(std::string)’ 参数丢弃限定符

转载 作者:行者123 更新时间:2023-11-28 08:09:10 24 4
gpt4 key购买 nike

我在使用部分 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 */
}

根据 documentation for 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 成为一个常量函数。它的名字暗示它应该是常量。不过,您可能无权更改该代码。

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

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

关于c++ - 传递 ‘const Link’ 作为 ‘this’ 的 ‘std::string GetAttribute(std::string)’ 参数丢弃限定符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9527003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com