C++如何正确地在类中初始化vector成员变量

2022年 11月 4日 91点热度 0人点赞

本文转自: https://blog.csdn.net/greenlight_74110/article/details/89137520

错误的方法

class Foo(){
private:
    vector<string> name(5); //error in these 2 lines
    vector<int> val(5, 0);
}

正确的方法

C++11 以后

class Foo(){
private:
    vector<string> name = vector<string>(5);
    vector<int> val{vector<int>(5, 0)};
}

C++11 以前

class Foo {
private:
    vector<string> name;
    vector<int> val;
 public:
  Foo() : name(5), val(5, 0) {}
};

file

rainbow

这个人很懒,什么都没留下

文章评论