我有一堂课
class A
{
public:
int N;
double .....
};
但是我希望.....定义一个取决于N的大小矩阵。如果改变了方法,它是N的一个不同函数,而不仅仅是N本身,例如N ^ 3 + 1。
编辑: N的值稍后在代码中确定。就像这样:
A InstanceOfA; //The variable InstanceOfA is declared of type A.
...
Some other stuff happens, e.g. other properties of InstanceOfA are initialized
and some of the functions are used. And then:
...
A.setN(4);
我不明白从下面的答案。我需要做吗
A InstanceOfA(4);
?
您可以使用 std::vector
class A
{
public:
int N; // you should use int for size
double std::vector<std::vector<double>> matrix; //define the matrix
//initialize it in the constructor
A( int size ):N(size), matrix(size*3+3)// or you can use any expression that evaluates an integral value
{
//you can initialize the values in matrix here
}
};
笔记
该表达式matrix(size*3+3)
初始化矩阵,使得存在size*3+3
rows,但尚未指定每行中的列数。您还可以在构造函数中指定列大小,例如
for( int i=0;i< N*3+3; ++i) //for each row
{
matrix[i].resize(N*2);// resize each col to hold N*2 cells,
}
编辑
根据所讨论的修改,您可以将构造函数保留为空(或初始化任何其他成员),并setSize
在class中提供一个方法A
,该方法稍后将初始化大小。
void setSize(int size){
N= size;
matrix.resize( size*3+3);
for( int i=0;i< N*3+3; ++i) //for each row
{
matrix[i].resize(N*2);// resize each col to hold N*2 cells,
}
}
然后,您可以像这样使用它:
A instanceOfA;
//other code
//
instanceOfA.setSize(N);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句