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/