1.错误信息
错误为
error: passing ‘const xxx’ as ‘this’ argument of ‘std::string xxx()’ discards qualifiers [-fpermissive]
实际中

2.错误分析
错误的原因就是,C++中const 引用的是对象时只能访问该对象的const 函数,因为其他函数有可能会修改该对象的成员,编译器为了避免该类事情发生,会认为调用非const函数是错误的。
意思是说 在一个加了const限定符的成员函数中,不能够调用非const成员函数。而error:…discards qualifiers 的意思就是缺少限定符。
比如
//=========================================================
//TcpConnection类中
void TcpConnection::showip() const
{
cout << "ip:" << _localAddr.ip_ntoa()
<< "port:" << _localAddr.port_ntoh() << endl
}
//==========================================================
//InetAddress类中
string InetAddress::ip_ntoa()
{
return string(inet_ntoa(_addr.sin_addr));
}
unsigned short InetAddress::port_ntoh()
{
return ntohs(_addr.sin_port);
}
//==========================================================
3.错误解决
给成员函数加上const
string InetAddress::ip_ntoa() const
{
return string(inet_ntoa(_addr.sin_addr));
}
unsigned short InetAddress::port_ntoh() const
{
return ntohs(_addr.sin_port);
}
本文详细解析了C++中遇到的'passing ‘const xxx’ as ‘this’ argument of ‘std::string xxx()’ discards qualifiers [-fpermissive]'错误,指出该错误源于尝试在const上下文中调用非const成员函数。通过分析错误原因,了解到const成员函数不能修改对象状态。解决方案是将涉及的成员函数声明为const。示例代码展示了如何修正该问题,确保在const对象上调用的成员函数不会改变对象状态。
3338

被折叠的 条评论
为什么被折叠?



