【发布时间】:2021-12-25 17:27:12
【问题描述】:
好的,我对编程和 c++ 还很陌生,所以请放轻松。我正在尝试编写一个程序,该程序采用金属板的尺寸进行二维有限元方法分析(忽略厚度)。因此,我为我的零件(板)创建了一个类,为网格创建了元素,为元素创建了节点。网格将由方形元素组成,并将应用于板的正面。现在,我正在着手整理网格,然后再继续讨论元素和节点类。
我正在使用(或想要使用)动态分配来创建一个包含网格元素的二维数组(我的网格)。我正在尝试编写一个函数“meshingPart”来创建二维数组,其中行数是板的高度,列是板的长度。
当我运行程序时,我得到了这些错误,我不知道如何修复它们:
In member function 'void PartClass::meshingPart(int&, int, int)':
error: invalid types 'int[int]' for array subscript
At global scope:
error: expected constructor, destructor, or type conversion before '(' token
另外,当我使用 printPart() 函数时,它会打印指针的地址还是数组的值?我对此并不完全确定,我对指针也很陌生。
任何帮助将不胜感激!提前致谢。
class PartClass
{
private:
const int HEIGHT; // mm
const int LENGTH; // mm
const int WIDTH; // mm
const int SEED; // mm
const int MESHROW;
const int MESHCOL;
int *partMesh; // Mesh array - an int pointer
// Creates the mesh for the part by generating elements to fill the width and length
// of the part. The elements are stored in a 2-D array.
void meshingPart(const int &partMesh, int inRow, int inCol);
public:
// Constructs a part with the given parameters, seeds the part for the mesh,
// then creates the mesh by generating square elements with length = height = SEED.
PartClass(int inHeight, int inLength, int inWidth, int inSeed);
void printPart()
{
cout << "Part mesh:" << *partMesh << endl;
}
};
class ElementClass
{
private:
int elemID;
static int numElems;
// Shape functions:
int N1;
int N2;
int N3;
int N4;
public:
// Default constructor
ElementClass()
{
elemID = numElems;
numElems++;
};
};
PartClass :: PartClass(inHeight, inLength, inWidth, inSeed)
{
HEIGHT = inHeight;
LENGTH = inLength;
WIDTH = inWidth;
SEED = inSeed;
MESHROW = HEIGHT/SEED;
MESHCOL = LENGTH/SEED;
// Dynamically declares an array, gets memory, assigns address to partMesh.
partMesh = new int[MESHROW][MESHCOL];
meshingPart(&partMesh, MESHROW, MESHCOL);
}
void PartClass :: meshingPart(int &partMesh, int inRow, int inCol)
{
for( int i; i < inRow; i++)
{
for( int j; j < inCol; j++)
{
partMesh[i][j] = ElementClass();
}
}
}
【问题讨论】:
-
问题似乎是拼写错误。你声明
PartClass(int inHeight...,然后定义PartClass(inHeight...(你忘了int)。你声明meshingPart(const int &partMesh...,然后定义meshingPart(int &partMesh...(你忘了const) -
您还需要了解constructor initialization lists。对于
const int HEIGHT,const表示“HEIGHT无法更改”。与此相反,HEIGHT = inHeight;的意思是“改变HEIGHT”。
标签: c++ pointers dynamic-memory-allocation new-operator dynamic-arrays