将“const Link”作为“std::string GetAttribute(std::string)”的“this
passing ‘const Link’ as ‘this’ argument of ‘std::string GetAttribute(std::string)’ discards qualifiers
我在使用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 方法确实是安全的。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然