std::map的类内初始化 我有C++代码的片段,它不在G++-4.91下编译,我使用了命令G++-C-STD= C++ 11 MAP.cc/P> #include <map> #include <cstdint> class A { std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>(); };
我在编译时遇到以下错误:std::map的类内初始化 我有C++代码的片段,它不在G++-4.91下编译,我使用了命令G++-C-STD= C++ 11 MAP.cc/P> #include <map> #include <cstdint> class A { std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>(); };,c++,c++11,gcc,C++,C++11,Gcc,我在编译时遇到以下错误: map.cc:5:52: error: expected ‘;’ at end of member declaration std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>(); ^ map.cc:5:52: error: declaration of ‘std::map&
map.cc:5:52: error: expected ‘;’ at end of member declaration
std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>();
^
map.cc:5:52: error: declaration of ‘std::map<unsigned char, unsigned char> A::uint8_t’ [-fpermissive]
In file included from /usr/lib/gcc/x86_64-linux-gnu/4.9/include/stdint.h:9:0,
from /usr/include/c++/4.9/cstdint:41,
from /usr/include/c++/4.9/bits/char_traits.h:380,
from /usr/include/c++/4.9/string:40,
from /usr/include/c++/4.9/stdexcept:39,
from /usr/include/c++/4.9/array:38,
from /usr/include/c++/4.9/tuple:39,
from /usr/include/c++/4.9/bits/stl_map.h:63,
from /usr/include/c++/4.9/map:61,
from map.cc:1:
/usr/include/stdint.h:48:24: error: changes meaning of ‘uint8_t’ from ‘typedef unsigned char uint8_t’ [-fpermissive]
typedef unsigned char uint8_t;
^
map.cc:5:59: error: expected unqualified-id before ‘>’ token
std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>();
^
map.cc:5:43: error: wrong number of template arguments (1, should be 4)
std::map<uint8_t, uint8_t> b = std::map<uint8_t, uint8_t>();
^
In file included from /usr/include/c++/4.9/map:61:0,
from map.cc:1:
/usr/include/c++/4.9/bits/stl_map.h:96:11: error: provided for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
class map
^
但是,如果我用int替换uint8_t,它的编译效果很好。FWIW,如果您需要解决方法,以下方法可以:
class A {
typedef std::map<uint8_t, uint8_t> B;
B b = B();
};
g++的问题要大得多,当您将模板用作类成员时,如果除第一个参数外的任何参数是typedef或在另一个命名空间中,就不能使用成员初始化
typedef int I;
template<typename T1, typename T2> struct A {};
struct B {
A<I,float> a1=A<I,float>(); // works!
A<float,I> a2=A<float,I>(); // does not compile!
// This is the same reason the map does not comile, as string is a typedef
};
这似乎是一个GCC问题。谢谢。它似乎是在clang++Ubuntu clang版本3.5.0-4ubuntu2下编译的。我可能应该搜索g++错误报告。请注意,正如您所看到的,类内初始化是毫无意义的,因为您只是在进行默认初始化,这将在没有任何帮助的情况下发生。std::map b=std::map;是对的uint8\u t是错的。这似乎是一个GCC问题。你能试试std::uint8\u t吗?没关系,使用GCC 4.8谢谢你的建议。对于我的具体问题,有一些变通方法,比如像Jerry指出的那样完全省略初始化。Fwiw,它也不适用于gcc-4.8/g++-4.8。