【问题标题】:Error when compiling Private member of class of type vector - C++ [duplicate]编译类型向量类的私有成员时出错 - C++ [重复]
【发布时间】:2018-02-12 01:52:52
【问题描述】:

我正在为扫雷游戏创建一个类。该类不带任何参数。私有成员在类中被初始化。我的目标是初始化一个二维整数向量。

using namespace std;

class Minesweeper {
public:
    //This class takes no parameters
    //Other methods will be here

private:
    int rows = 20;
    int cols = 20;
    vector < vector <int>> theBoard(rows, vector<int>(cols));
};

我收到的编译错误如下:(都与向量初始化一致)

  1. 找不到“theBoard”的函数定义
  2. 成员“Minesweeper::rows”不是类型名称

我不明白上述错误。我相信我在创建二维向量时使用了正确的语法。将不胜感激任何帮助。

【问题讨论】:

    标签: c++ class vector


    【解决方案1】:

    为你的类添加一个构造函数。例如,

    class Minesweeper
    {
        public:
            Minesweeper()
            : rows(20),
              cols(20),
              theBoard(rows, vector<int>(cols))
            {
    
            }
    
        private:
            int rows, cols;
    
            vector<vector<int>> theBoard;
    };
    

    【讨论】:

    • 这里不需要构造函数。所有成员都已正确初始化。
    • @Nikos, theBoard 是成员变量,而不是方法。
    • 这也可以:vector&lt;vector&lt;int&gt;&gt; theBoard{static_cast&lt;size_t&gt;(rows), vector&lt;int&gt;{cols}}; 这避免了编写 ctor 的需要。
    【解决方案2】:

    这是一个“MVP”(最令人头疼的解析)示例。有关该问题的更多信息,请参阅已复制的问题。

    但是,我仍然在这里给出关于如何正确初始化theBoard 的答案,因为通常情况下,你会这样写:

    vector<vector<int>> theBoard{rows, vector<int>{cols}};
    

    但这不起作用,因为在使用初始化列表时,rows 不能隐式转换为 size_t。所以你需要这个:

    vector<vector<int>> theBoard{static_cast<size_t>(rows), vector<int>{cols}};
    

    您可以将rowscolsint 改为size_t,但不建议使用size_t(或一般无符号整数)作为数量。 (vector 使用无符号整数作为其大小几乎是 C++ 中的语言缺陷,现在无法修复,因为它会破坏太多代码。)

    【讨论】:

      猜你喜欢
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 2016-04-30
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多