c++ - 想通过使用带变量的构造函数来声明数组

标签 c++ arrays constructor initialization destructor

class matrix
{

public:

    matrix();
    matrix(int row, int column);
    ~matrix();

private:

    const int DEFAULT_SIZE;

    int size_row, size_column;
    double *entry;
};

// main function
int
main()
{
    //make a matrix of default size
    matrix A;   /* no error */
    delete A;

    //make 5 matrices of default size
    matrix *B = new matrix [5]; /* no error */
    delete [] B;

    //make a matrix of size 15x15
    matrix C(15, 15);   /* no error */
    delete C;

    //make 5 matrices of size 15x15
    matrix *D = new matrix(15, 15) [5]; /* compile error !! */


    return 0;
}



//Define functions

matrix::matrix() : DEFAULT_SIZE(10)
{
    size_row = DEFAULT_SIZE;
    size_column = DEFAULT_SIZE;

    entry = new double [size_row*size_column];
}

matrix::matrix(int row, int column) : DEFAULT_SIZE(10)
{
    size_row = row;
    size_column = column;

    entry = new double [size_row*size_column];
}

matrix::~matrix()
{
    delete [] entry;
}

我正在研究构造函数。 我想通过使用带变量的构造函数来声明数组。 你能更正我的代码行吗?

请参阅下面的行“//制作 5 个大小为 15x15 的矩阵”

另外,在这种情况下,我该如何使用析构函数呢?

最佳答案

要创建一个由 5 个元素组成的数组,每个元素都用 (15,15) 构造,您可以在 C++11 中执行以下操作:

matrix* D = new matrix[5]{
    {15,15}, {15,15}, {15,15}, {15,15}, {15,15}
};

但是使用vector会简单得多:

std::vector<matrix> D(5, {15,15});        // C++11
std::vector<matrix> D(5, matrix(15,15));  // pre-C++11

关于c++ - 想通过使用带变量的构造函数来声明数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30035065/

相关文章:

android - 如何链接 cpufeatures lib 以获取 native android 库?

c++ - 在 C++ 的 Winsock 中发送 HTTP GET 请求后,Recv() 函数挂起

java - 集合中的整数数组

c# - 文字字符串赋值会像这样调用 String 构造函数吗?

c++ - Google 使用全局 vector 测试 ValuesIn

C++ 从对列表中删除

javascript - javascripts indexOfKey 是如何工作的

c - 取消引用结构体中的数组(在 C 中)

java - 传递一个字符串作为构造函数参数并获取 "illegal start of type"

c# - : this() As a constructor