2012-03-02 54 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

相關問題