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);
}