简体   繁体   English

如何在C ++中没有默认构造函数的情况下生成动态空2D数组

[英]How to generate dynamic empty 2D array without default constructor in C++

I have a class named Test and I'd like to create empty 2D array that will hold instances of that class and than add them later one by one using constructor that accepts parameters. 我有一个名为Test的类,我想创建一个空的2D数组,该数组将保存该类的实例,然后使用接受参数的构造函数一个接一个地添加它们。

Basically, I'd just like to reserve memory that I will fill in later with objects. 基本上,我只想保留以后将用对象填充的内存。 It needs to bee on a heap since I will have class that will generate 2D arrays of different sizes. 它需要在heap蜜蜂,因为我将拥有将生成不同大小的2D数组的类。

This was my first approach but it doesn't really work since Test class doesn't have default constructor: 这是我的第一种方法,但是由于Test类没有默认构造函数,因此它实际上不起作用:

Test** arr;
arr = new Test*[10];
for (int i = 0; i < 10; i++)
    arr[i] = new Test[10];

[EDIT] [编辑]

Here is my full test code. 这是我完整的测试代码。 All in all, I'm getting wrong values out, it should be numbers from 0 to 99: 总而言之,我输入的值有误,应该是0到99之间的数字:

#include <iostream>
using namespace std;

class Test {
private:
    short number;
public:
    Test(short n) {
        this->number = n;
    }
    short getNumber() {
        return number;
    }
};

int main() {
    Test** arr;
    arr = new Test*[10*10];
    for (int i = 0; i < 100; i++)
        arr[i] = new Test(i);
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++)
            cout << arr[i][j].getNumber() << " ";
        cout << endl;
    }
}

也许尝试使用带有默认参数的默认构造函数?

Test(int i = 0) {. . .}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM