【问题标题】:std::vector ctor compiles outside of class, but not inside?std::vector ctor 在类外编译,但不在类内?
【发布时间】:2013-11-10 06:48:18
【问题描述】:

为什么explicit vector (size_type n) 表单在类外有效,但在类内无效? 这样编译:

#include <vector>

int main() {
    std::vector<int> vec_(3); // set capacity to 3
    return 0;
}

但不是这个:

#include <vector>

class C {
public:
    std::vector<int> vec_(3); // set capacity to 3
};

int main() {
    return 0;
}

g++ --std=c++0x -Wall -Wextra  -g a.cpp
a.cpp:5:27: error: expected identifier before numeric constant
a.cpp:5:27: error: expected ‘,’ or ‘...’ before numeric constant

为什么? :(

【问题讨论】:

  • 这不是您在类中初始化数据成员的方式。谁教你的?
  • 因为你通过类构造函数调用成员构造函数。

标签: c++ class vector constructor


【解决方案1】:

正确的做法是:

class C {
public:
    C() : vec_(3) {} // set capacity to 3 in constructor initialization list
    std::vector<int> vec_;
};

【讨论】:

    【解决方案2】:

    你想要的是:

    class C {
    public:
        std::vector<int> vec_;
        C() : vec_(3) { }
    };
    

    这将控制在您构造 C 对象时如何构造 vec_

    【讨论】:

      【解决方案3】:

      因为这不是 C++ 中的有效语法。正确的做法是:

      #include <vector>
      
      class C {
      public:
          std::vector<int> vec_;
      
      public:
          // You add a constructor and initialize member data there:
          C () : vec_(3) {}
      };
      

      还有其他方法可以做到这一点,但这是使用最广泛且易于使用的方法。

      【讨论】:

        猜你喜欢
        • 2020-04-17
        • 2014-05-12
        • 2013-10-07
        • 2023-03-22
        • 2021-05-21
        • 2018-08-09
        • 2022-01-03
        • 2014-12-27
        • 2010-10-06
        相关资源
        最近更新 更多