错误为
error: passing ‘const sn::InetAddress’ as ‘this’ argument of ‘std::string sn::InetAddress::ip_ntoa()’ discards qualifiers [-fpermissive]
摘出相关错误代码:
//=========================================================
//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);
}
//==========================================================
错误的原因很简单,C++中const 引用的是对象时只能访问该对象的const 函数,因为其他函数有可能会修改该对象的成员,编译器为了避免该类事情发生,会认为调用非const函数是错误的。
意思是说 在一个加了const限定符的成员函数中,不能够调用 非const成员函数。而error:…discards qualifiers 的意思就是缺少限定符。
解决方法是 InetAddress::ip_ntoa() 和 InetAddress::port_ntoh() 函数加const修饰this,表示不会修改该对象的成员。如下:
string InetAddress::ip_ntoa() const
{
return string(inet_ntoa(_addr.sin_addr));
}
unsigned short InetAddress::port_ntoh() const
{
return ntohs(_addr.sin_port);
}