c++ 11g++使用大括号括起来的初始化列表

C++11 g++ with brace-enclosed initializer lists

本文关键字:起来 初始化 列表 c++ 11g++      更新时间:2023-10-16

我是编程新手,所以如果这是一个明显的问题,我很抱歉,但是我在一本书中遇到了语法问题(c++的创造者Bjarne Stroustrup编写的c++编程原则和实践第二版)。其中介绍了创建字符串向量的方法:

vector<string> philosopher
    ={"Kant","Plato","Hume","Kierkegaard"};

然而,当它通过g++传递时,它不喜欢它。我的代码如下:

#include "std_lib_facilities.h"  //The author's library for his examples
int main()
{
  vector<string>philosopher
    ={"Kant","Plato","Hume","Kierkegaard"};
}

我得到一个错误编译:

g++ vecttest.cpp -std=c++11
In file included from /usr/local/include/c++/4.9.0/ext/hash_map:60:0,
             from /usr/include/std_lib_facilities.h:34,
             from vecttest.cpp:1:
/usr/local/include/c++/4.9.0/backward/backward_warning.h:32:2: warning: #warning 
This file includes at least one deprecated or antiquated header which may 
be removed without further notice at a future date. Please use a 
non-deprecated interface with equivalent functionality instead. For a listing     
of replacement headers and interfaces, consult the file backward_warning.h. 
To disable this warning use -Wno-deprecated. [-Wcpp]
#warning 
^
In file included from /usr/local/include/c++/4.9.0/locale:41:0,
             from /usr/local/include/c++/4.9.0/iomanip:43,
             from /usr/include/std_lib_facilities.h:212,
             from vecttest.cpp:1:
/usr/local/include/c++/4.9.0/bits/locale_facets_nonio.h:1869:5: error: 
template-id  ‘do_get<>’ for 
‘String std::messages<char>::do_get(std::messages_base::catalog, int, int, 
const String&) const’ does not match any template declaration
 messages<char>::do_get(catalog, int, int, const string&) const;
 ^
/usr/local/include/c++/4.9.0/bits/locale_facets_nonio.h:1869:62: note: 
saw 1 ‘template<>’, need 2 for specializing a member function template
 messages<char>::do_get(catalog, int, int, const string&) const;
                                                          ^
vecttest.cpp: In function ‘int main()’:
vecttest.cpp:8:42: error: could not convert ‘{"Kant", "Plato", 
"Hume","Kierkegaard"}’from ‘<brace-enclosed initializer list>’ to ‘Vector<String>’
 ={"Kant","Plato","Hume","Kierkegaard"};

我想可能我的GCC版本较旧(它是4.7),所以我将其更新为4.9:

g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-unknown-linux-gnu/4.9.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: ../gcc-4.9.0/configure
Thread model: posix
gcc version 4.9.0 (GCC) 

你知道我哪里错了吗?

非常感谢您的帮助

你使用这个std_lib_facilities.h是错误的。在网上看,它显示:

template< class T> struct Vector : public std::vector<T> {
    ...
};
// disgusting macro hack to get a range checked vector:
#define vector Vector

不幸的是,这个自定义Vector模板类缺少std::vector所具有的一些构造函数。

直接使用std::vector,它将工作。它在GCC 4.4及更新版本中得到支持。

注意:要使用std::vector,您需要确保根本不使用std_lib_facilities.h,或者使用#undef vector。宏定义是有问题的,并且不关注名称空间,因此std::vector将成为不存在的std::Vector

注释2:T.C.正确地指出string也存在类似的问题:请使用std::string代替。