[英]static const int as map subscript
I ran into a strange issue. 我遇到了一个奇怪的问题。 Considering this example:
考虑这个例子:
class Foo
{
static const int Bar = 5;
public:
Foo()
{
_map[Bar] = "some characters";
}
~Foo() {}
private:
std::map<int, std::string> _map;
};
int main()
{
Foo a;
return (0);
}
I get this error (compiling with g++ 4.7.2): 我收到此错误(使用g ++ 4.7.2编译):
/tmp/ccLy806T.o: In function `Foo::Foo()':
Main.cpp:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x1e): undefined reference to `Foo::Bar'
Now, if I make a static_cast on Bar, it works: 现在,如果我在Bar上进行static_cast,它可以工作:
Foo()
{
int i = Bar; //works
_map[static_cast<int>(Bar)] = "some characters"; //works
}
This error only appears when using Bar
as map subscript in the constructor. 仅在构造函数中使用
Bar
作为映射下标时才会出现此错误。 Writing _map[Bar] = "some characters";
写
_map[Bar] = "some characters";
in an other function in the Foo class doesn't produce any error. 在Foo类的另一个函数中不会产生任何错误。
That's really strange for me, but I expect that someone here has an answer. 这对我来说真的很奇怪,但我希望有人在这里有答案。
So, what am I doing wrong ? 那么,我做错了什么?
That's because map::operator[]
takes its key as a int const&
. 那是因为
map::operator[]
将其键作为int const&
。 It wants the address of the thing you're passing into it. 它想要你传递给它的东西的地址。 When you do:
当你这样做时:
_map[static_cast<int>(Bar)]
you're creating a temporary, and passing in the address to that temporary, which is fine. 你正在创建一个临时的,并将地址传递给那个临时的,这很好。 But when you're doing:
但是当你做的时候:
_map[Bar]
Bar
doesn't actually have memory storage. Bar
实际上没有内存存储空间。 You need to provide it via: 您需要通过以下方式提供:
class Foo {
....
};
const int Foo::Bar;
您需要在顶层添加以下内容以为Foo::Bar
分配存储空间:
const int Foo::Bar;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.