以下代码段在g ++(版本4.73)上给出了错误。我一定有些傻事。
$g++ -std=c++11 te2d.cc
te2d.cc:61:7: error: ‘MyMacHash’ is not a template
te2d.cc: In member function ‘size_t MyMacHash::operator()(const cMacAddr&) const’:
te2d.cc:63:83: error: passing ‘const cMacAddr’ as ‘this’ argument of ‘long int cMacAddr::toLong()’ discards qualifiers [-fpermissive]
源代码
#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <malloc.h>
#include <unordered_map>
#include <string>
using namespace std;
typedef unsigned char uchar;
class cMacAddr {
public:
uchar addr[6];
cMacAddr(uchar *newAddr) { for (int i=0; i<6; i++) addr[i] = newAddr[i];}
cMacAddr(const char *newAddr) { for (int i=0; i<6; i++) addr[i] = newAddr[i];}
bool operator == (uchar *newAddr) {
for (int i=0; i<6; i++) if (addr[i] != newAddr[i]) return false;
return true;
}
bool operator == (unsigned long newAddr) {
unsigned long tmp = 0;
for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
return tmp == newAddr;
}
bool operator == (cMacAddr &m) {
for (int i=0; i<6; i++) if (addr[i] != m.addr[i]) return false;
return true;
}
bool operator != (unsigned long newAddr) {
unsigned long tmp = 0;
for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
return tmp != newAddr;
}
operator long () {
return this->toLong();
}
long toLong() {
unsigned long tmp = 0;
for (int i=0; i<6; i++) tmp = (tmp << 8) + addr[i];
return tmp;
}
string toString() {
char buf[30];
int i;
int offset = 0;
for (i=0; i<6; i++) {
if (i) { buf[offset] = ':'; offset ++; }
offset += sprintf(&buf[offset], "%02x", addr[i]);
}
return string(&buf[0]);
}
uchar operator [] (int id) { return addr[id]; }
uchar * ptr() { return &addr[0];}
};
class MyMacHash {
public:
size_t operator()(const cMacAddr& m) const { return std::hash<long>() (m.toLong()); }
};
typedef std::unordered_map< cMacAddr, long, MyMacHash > m2imap;
int main (int argc, char *argv[]) {
m2imap x;
return 0;
}
答案 0 :(得分:2)
此错误:
te2d.cc: In member function ‘size_t MyMacHash::operator()(const cMacAddr&) const’:
te2d.cc:63:83: error: passing ‘const cMacAddr’ as ‘this’ argument of ‘long int cMacAddr::toLong()’ discards qualifiers [-fpermissive]
指的是你的哈希函子接受const cMacAddr& m
,但你调用m.toLong()
,这不是const函数。
您应将toLong
声明为const
,即
long toLong() const {