类成员变量初始化问题研究(vector 初始化)

本文最后更新于:2025年6月2日 下午

类成员变量初始化问题研究(vector 初始化)

刷leetcode时遇到的小问题

问题描述

1
2
3
4
5
6
class Solution {
public:
int ans = 0;
vector<vector<int>> board(9, vector<int>(9, 0));
// 其他方法
};

编译错误

1
2
3
Line 4: Char 31: error: expected parameter declarator
4 | vector<vector<int>> board(9, vector<int>(9, 0));
|

错误原因

在 C++ 类的定义中:

  1. 非静态成员变量不支持使用圆括号进行直接初始化。
  2. 初始化列表一般是在构造函数里使用。
  3. 要是想在类定义时初始化成员变量,得使用花括号初始化(C++11 及以后版本)或者静态常量表达式。

解决办法

可以采用以下几种方式来解决这个问题:

方法 1:运用花括号初始化

1
2
3
vector<vector<int>> board = vector<vector<int>>(9, vector<int>(9, 0));
// 或者简化成
vector<vector<int>> board{9, vector<int>(9, 0)};

方法 2:在构造函数的初始化列表中进行初始化

1
2
3
4
5
6
7
8
class Solution {
public:
int ans = 0;
vector<vector<int>> board;

Solution() : board(9, vector<int>(9, 0)) {} // 构造函数初始化列表
// 其他方法保持不变
};

方法 3:先声明变量,再在构造函数里赋值

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int ans = 0;
vector<vector<int>> board;

Solution() {
board = vector<vector<int>>(9, vector<int>(9, 0));
}
// 其他方法保持不变
};

类成员变量初始化问题研究(vector 初始化)
https://furthur509.github.io/2025/06/02/类成员变量初始化问题研究(vector 初始化)/
作者
Yang Mingxin
发布于
2025年6月2日
许可协议