gpt4 book ai didi

c++ - 定义哈希类时编译错误

转载 作者:行者123 更新时间:2023-11-30 02:37:01 26 4
gpt4 key购买 nike

以下代码片段在 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;
}

最佳答案

这个错误:

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,但您调用的不是 const 函数的 m.toLong()

您应该将toLong 声明为const,即

long toLong() const {

关于c++ - 定义哈希类时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32080809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com