了解构造函数定义块的句法变体
Understanding syntactic variations of a constructor definition block
我认为我的问题类似于 ,但对于 C++,而不是 C#(尽管相同的答案可能适用于两者)。
我的问题也类似于this one(其中已被标记为重复)。然而,差异 是关于 构造函数原型[ 的问题=40=],而我的询问 构造函数定义块 .
考虑以下构造函数定义块:
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
: m_data(rows * cols, initVal)
, m_rows(rows)
, m_cols(cols)
{}
我是 C++ 新手,CallOne() : call_two(), call_three(), call_four() {}
语法让我感到困惑。
是否等价于下面的代码块?
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
{
vector <T> m_data(rows * cols, initVal);
m_rows = rows;
m_cols = cols;
}
请注意,在 SimpleMatrix
class 定义中,m_data
、m_rows
和 m_cols
在 private
块中声明为如下:
private:
int m_rows;
int m_cols;
vector<T> m_data;
NOTE: Whether this question is a duplicate would be grounds for some debate. In technical terms, yes, it is, and I agree with marking it as such. For a complete newbie, however, it may be hard to derive the answer from the duplicate. This answer, plus the duplicate question, create the whole picture.
笼统地说,其实是一样的。
第一个是初始化列表,它初始化每个变量。第二个是分配值。
要理解为什么第一个通常更优越,我们必须了解第二个。当我们在构造函数中给一个变量赋值时,代码必须首先用一些默认值初始化它,然后将我们想要的值赋给那个新初始化的变量。因此,它需要两个步骤。
当我们使用初始化列表时,我们使用我们选择的值初始化变量,而不是自动选择的值。因此,它只需要一步。
看似迂腐的小细节,但点点滴滴都有助于优化。
无论出现在构造函数的 header 还是实现中,这都是相同的概念。
我认为我的问题类似于
我的问题也类似于this one(其中已被标记为重复)。然而,差异 是关于 构造函数原型[ 的问题=40=],而我的询问 构造函数定义块 .
考虑以下构造函数定义块:
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
: m_data(rows * cols, initVal)
, m_rows(rows)
, m_cols(cols)
{}
我是 C++ 新手,CallOne() : call_two(), call_three(), call_four() {}
语法让我感到困惑。
是否等价于下面的代码块?
template <class T>
SimpleMatrix<T>::SimpleMatrix(int rows, int cols, const T& initVal)
{
vector <T> m_data(rows * cols, initVal);
m_rows = rows;
m_cols = cols;
}
请注意,在 SimpleMatrix
class 定义中,m_data
、m_rows
和 m_cols
在 private
块中声明为如下:
private:
int m_rows;
int m_cols;
vector<T> m_data;
NOTE: Whether this question is a duplicate would be grounds for some debate. In technical terms, yes, it is, and I agree with marking it as such. For a complete newbie, however, it may be hard to derive the answer from the duplicate. This answer, plus the duplicate question, create the whole picture.
笼统地说,其实是一样的。
第一个是初始化列表,它初始化每个变量。第二个是分配值。
要理解为什么第一个通常更优越,我们必须了解第二个。当我们在构造函数中给一个变量赋值时,代码必须首先用一些默认值初始化它,然后将我们想要的值赋给那个新初始化的变量。因此,它需要两个步骤。
当我们使用初始化列表时,我们使用我们选择的值初始化变量,而不是自动选择的值。因此,它只需要一步。
看似迂腐的小细节,但点点滴滴都有助于优化。
无论出现在构造函数的 header 还是实现中,这都是相同的概念。