c++ - 关于 new[][] 和初始化数组中的类

标签 c++ arrays constructor

#include <iostream>
using namespace std;

class CType{
private:
    int val;
public:
    CType(): val(0){}
    CType(int x): val(x){}
    void setVal(int x){ val = x; }
    ~CType(){ cout << val << " is destructed." << endl;} 
};

int main(){
    // CType *t = new CType[10](10); // -1-
    CType (*t)[10] = new CType[10][10]; // -2-
    for(int i = 0; i < 10; ++i){
        for(int j = 0; j < 10; ++j){
            t[i][j].setVal(10 * i + j);
        }
    }
    delete[] t;
    return 0;
}

上面的代码是我为了测试new[][]以及是否可以在动态数组中初始化实例而写的一个示例。我的问题是:

  1. 我打算创建一个包含 10 个 CType 实例的数组,并将 val 初始化为 10。但是这一行无法通过编译。我必须添加一个没有参数的默认构造函数和 CType *t = new CType[10]。有什么方法可以创建实例数组并使用一些参数调用构造函数吗?

  2. 我对 new int[10][10] 感到困惑,它直观地创建了一个 10x10 二维数组。但是我找不到任何定义 new int[][]new int[][][] 等行为的官方资料。为什么 new int[ 10][10] 具有返回类型 int (*)[10] 而不是 int**int[10][10]?

顺便说一句,如果我写 CType (*t)[10] = new CType[10][10](10),我会在读取 A.cpp 时遇到编译错误:13:39:抱歉,未实现:无法使用初始化程序初始化多维数组。有趣的是,g++ 说对不起。


更新

我正在使用 g++。但我还在 VS2010 上测试了代码。它通过编译并输出与在 g++ 中相同的结果。

CType (*t)[10] 中的变量t 是一个指针,指向一个包含 10 个 CType 实例的数组,而不是一个包含 10 个 CType 指针的数组。所以 t + 1 指向 sizeof(CType) * 10 字节之后的位置 t

我的代码的输出显示 delete[] t 的析构顺序是 99 到 0。t + 9 的最后一个元素首先被析构。

最佳答案

Is there any way to create an array of instances and invoke constructors with some parameters?

从 C++11 开始就有了:

CType* t = new CType[10] {10, 10, 10, 10, 10, 10, 10, 10, 10, 10};
// ...
delete[] t;

但一般来说,在 C++ 中使用 vector 要好得多:

std::vector<CType> t(10);
// ...
// no need to delete anything manually!

I cannot find any official material defining the behavior of new int[][] or new int[][][] etc.

5.3.4 [expr.new] §5 说:

When the allocated object is an array [...], the new-expression yields a pointer to the initial element (if any) of the array.

Note: both new int and new int[10] have type int* and the type of new int[i][10] is int (*)[10]


Why does new int[10][10] have return type int (*)[10] rather than int**

它不能是 int**,因为这样一个简单的 delete[] 是不够的。

or int[10][10]?

因为 int[10][10] 不是指针,但是 new 总是返回一个指针。

关于c++ - 关于 new[][] 和初始化数组中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125433/

相关文章:

c++ - borland turbo c++ 4.5 中的 FMOD 错误

c++ - Qt- 改变 QPixmap 的不透明度

C++ 奇怪的套接字数据

c++ - 动态分配和数组/指针的段错误

c++ - 在头类构造函数中使用嵌套类

c++ - 捕获最后一个 WM_SIZE

java - 在oracle存储过程中传递数组

php - 在数组中设置嵌套项

Javascript在数组中使用构造函数

C++ 构造函数 : garbage while initialization of const reference