简体   繁体   中英

No match to std::vector<Foo> when specifying vector size in constructor

class Foo {
    vector<Bar> bars;
  public:
    Foo(int barcount) : { bars(barcount, 0); };
};

I'm trying to turn the bars vector into a vector holding barcount Bars. However I get 2 errors when doing this:

Foo.cpp:8: error: expected identifier before ‘{’ token
Foo(int barcount) : { bars(barcount, 0); };
                           ^
Foo.cpp:8: error: no match for call to ‘(std::vector<Bar>) (int&, int)’
Foo(int barcount) : { bars(barcount, 0); };

Any help on what might be going wrong would be much appreciated.

EDIT: This is my code now (Foo/Bar replaced):

class Machine {
    vector<Rotor> rotors;
  public:
    Machine(int rotorcount) : rotors(rotorcount, 0) {}
};

And I get a pretty long error message:

/usr/include/c++/4.8/bits/stl_vector.h: In instantiation of ‘void std::vector<_Tp, _Alloc>::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int; _Tp = Rotor; _Alloc = std::allocator<Rotor>]’:
/usr/include/c++/4.8/bits/stl_vector.h:404:55:   required from ‘std::vector<_Tp, _Alloc>::vector(_InputIterator, _InputIterator, const allocator_type&) [with _InputIterator = int; _Tp = Rotor; _Alloc = std::allocator<Rotor>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Rotor>]’
Machine.cpp:8:51:   required from here
/usr/include/c++/4.8/bits/stl_vector.h:1166:59: error: no matching function for call to ‘std::vector<Rotor>::_M_fill_initialize(std::vector<Rotor>::size_type, int&)’
    _M_fill_initialize(static_cast<size_type>(__n), __value);
                                                           ^
/usr/include/c++/4.8/bits/stl_vector.h:1166:59: note: candidate is:
/usr/include/c++/4.8/bits/stl_vector.h:1212:7: note: void std::vector<_Tp, _Alloc>::_M_fill_initialize(std::vector<_Tp, _Alloc>::size_type, const value_type&) [with _Tp = Rotor; _Alloc = std::allocator<Rotor>; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = Rotor]
       _M_fill_initialize(size_type __n, const value_type& __value)
       ^
/usr/include/c++/4.8/bits/stl_vector.h:1212:7: note:   no known conversion for argument 2 from ‘int’ to ‘const value_type& {aka const Rotor&}’

初始化列表位于逗号之后,但位于构造函数主体之前,并且后没有分号:

Foo(int barcount) : bars(barcount, 0) {};
no known conversion for argument 2 from ‘int’ to ‘const value_type& {aka const Rotor&}’

听起来好像您没有将int作为单个参数的构造函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM