问题描述
我需要帮助的东西真的很简单,这C ++使得很难。我创建了一个类,lattice,目的是初始化和处理一个矩阵。有以下私人成员:
I need help in something really simple, which C++ makes very difficult. I created a class, lattice, with the aim to initialize and treat a matrix. There are the following private members:
private unsigned dim;
private double matrix [dim][dim];
我想通过参数初始化类的构造函数中的变量dim,继续返回错误。我试图使昏暗的公共和静态和初始化它在主程序,但仍有问题。如何创建这个简单的类?
I would like to initialize the variable dim in the constructor of the class through a parameter, but the compiler continue to return errors. I tried to make dim public and static and initializing it in the main program, but there are still problems. How could I create this simple class?
此外,我还在类中实现了一些方法,以更新矩阵的值。是真的,在主程序中初始化一个类的对象,然后使用它的更新方法,矩阵的值只存储一次?
Moreover, I also implemented some methods in the class in order to update the values of the matrix. Is it true that, initializing an object of the class in a main program and then using its "updating" methods, the values of the matrix are stored only once?
谢谢
推荐答案
创建这样的类有三种方法(至少):
There are (at least) three ways to create such a class:
-
使用
模板
template<size_t dim>
class Matrix
{
private:
double matrix[dim][dim];
}
c> std :: vector (例如 valarray
也可以工作)
#include <vector>
class Matrix
{
private:
size_t dim;
std::vector<std::vector<double> > matrix;
public:
Matrix(size_t dim_) : dim(dim_), matrix()
{
matrix.resize(dim);
for ( size_t i = 0; i < dim; ++i )
matrix[i].resize(dim);
}
}
不推荐!)
with the use of plain arrays (I do not recommend that!)
class Matrix
{
private:
size_t dim;
double** matrix;
public:
Matrix(size_t dim_) : dim(dim_), matrix()
{
matrix = new double*[dim];
for ( size_t i = 0; i < dim; ++i )
matrix[i] = new double[dim];
}
~Matrix() // you need a destructor!
{
for ( size_t i = 0; i < dim; ++i )
delete [] matrix[i];
delete [] matrix;
}
}
这篇关于C ++:如何通过其构造函数的参数初始化类中的矩阵的维度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!