gpt4 book ai didi

c++ - C++中带()的内在类型的含义

转载 作者:可可西里 更新时间:2023-11-01 18:29:10 24 4
gpt4 key购买 nike

当内部类型带有括号运算符时,这意味着什么。

例如int() 或 float()

它是像默认构造函数还是对内部类型有不同的含义?

----编辑----

添加更多上下文:

在我的 C++ 学校教科书中,有一章是关于模板的。用于演示的模板是 Table 模板(二维数组)。 Table 的函数之一是 resize 方法,用于更改表格的尺寸,也用于 Table 的一些构造函数中。有问题的构造函数和 resize 方法是:

template <typename T> 
Table<T>::Table<T>(int m, int n)
{
mDataMatrix = 0;
mNumRows = 0;
mNumCols = 0;
resize(m, n, T());
}

template <typename T> 
void Table<T>::resize(int m, int n, const T& value)
{
// Destroy the previous data.
destroy();

// Save dimensions.
mNumRows = m;
mNumCols = n;

// Allocate a row (array) of pointers.
mDataMatrix = new T*[mNumRows];

// Now, loop through each pointer in this row array.
for(int i = 0; i < mNumRows; ++i)
{
// And allocate a column (array) to build the table.
mDataMatrix[i] = new T[mNumCols];

// Now loop through each element in this row[i]
// and copy 'value' into it.
for(int j = 0; j < mNumCols; ++j)
mDataMatrix[i][j] = value;
}
}

在构造函数定义中,resize 的第三个参数是 T()(我假设 T 成为模板是)。

resize 的定义中,T() 用于value 参数,为表中的元素分配一个默认值.

从之前的一些回答来看,这是零初始化。我假设这意味着表中每个元素的值都是 0(或者如果类型是 string,我猜是 0 的某个等价物)。这是正确的吗?

最佳答案

value initialization .

例如auto x = int(); 表示 int x = 0

在提供的示例中,T() 将创建一个类型为 T 的对象并将其作为参数传递。

你也可以这样写:

resize(m, n, T{}); 

关于c++ - C++中带()的内在类型的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40074193/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com