std::vector size in header

这一生的挚爱 提交于 2019-12-07 17:18:28

Assuming foo is a data member, your syntax is invalid. In general, you can initialize a data member of type T like this:

T foo{ctor_args};

or this

T foo = T(ctor_args);

However, std::vector<int> has a constructor that takes an std::initializer_list<int>, which means that the first form would yield a size-1 vector with a single element of value 7. So you are stuck with the second form:

std::vector<int> foo = std::vector<int>(7);

If you are stuck with a pre-C++11 compiler, you would need to use a constructor:

class bar
{
public:
    bar() : foo(7) {}
private:
  std::vector<int> foo;
};

and take care to initialize the vector in all constructors (if applicable.)

The most efficient way to initialize a class member (other than built-in type), is to use the initialisation list.

So the best solution here, is to construct your vector of length 7 in the initilization list of your class constructor:

(I also recommend you to use a define for your fixed value 7. If you change it to 8 in the futur your will not have to change the value 7 on all your code)

file.h:

#define YOURCLASSFOOSIZE 7
class yourClass
{
public:
    yourClass(): foo(YOURCLASSFOOSIZE) {}
private:
    std::vector<int> foo;
};

file.cpp :

for(int i=0; i < YOURCLASSFOOSIZE; i++)
{
    foo.push_back(0);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!