2012-03-02 70 views
0

我收到了NS-3 API部分的奇怪错误。这是我的错误信息:将'const Link'作为'std :: string'的'this'参数传递给'GetAttribute(std :: string)'丢弃限定符

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 */ 
    } 

我认为它可能与事实GetAttribute(std::string)不是const函数来完成,根据documentation for TopologyReader::Link,而其他函数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) 
+0

Ooops。我错过了,对不起。你可能想把这个报告为一个错误。它看起来像一个。 – 2012-03-02 02:13:40

回答

1

你的分析是正确的。明显的解决办法是使GetAttribute成为一个常量函数。它的名字暗示它应该是是const。不过,它可能没有能力改变这些代码。

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

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

+0

由于'LinksIterator'没有被定义,所以我必须使用'const_cast'方法。我如何去做这件事?我是否需要将该函数强制转换为'const'? (我对C++相当陌生) – kibibyte 2012-03-02 02:14:04

+1

@kibibyte'const_cast (* iter).GetAttribute ...' – 2012-03-02 02:15:42

+0

哦,亲爱的,这是相当可怕的语法。但它现在起作用了。谢谢! – kibibyte 2012-03-02 02:22:09

相关问题