这是一个极其愚蠢的问题,但这里是......
我有一个包含以下代码的类:
class ArraySection {
public:
unsigned char *array;
int start, stop, k;
};
我想做的就是在我的主函数中创建此类的实例。我正在尝试用这个(其中长度和n是预定义的)来做到这一点:
ArraySection *ASarrayPrimes = nullptr;
ASarrayPrimes->array[length];
ASarrayPrimes->start = stop;
ASarrayPrimes->stop += length;
ASarrayPrimes->k = 0;
但我猜这不是正确的方法......?我们从来没有在类里面真正讨论过这个问题。 (如果您想知道,我应该使用线程并行化筛算法来查找素数。)我想做的是采用大规模数组,将其分解为较小的数组(使用此 ArraySection 创建教授给出的类(class)),然后让线程在这些单独的较小线程中查找素数。
编辑:我无法改变类(class),伙计们。我只能按照教授给出的内容进行工作。
最佳答案
您永远不会为您的对象分配任何内存。要么用 new
分配内存,或将其保留在堆栈中。
您可以使用任一选项在类内分配数组。
ArraySection *ASarrayPrimes = new ArraySection; // On the heap
ASarrayPrimes->array = new char[SIZE]; // New character array on the heap
delete [] ASarrayPrimes->array;
delete ASarrayPrimes; // Make sure you free the memory
ArraySection ASarrayPrimes; // On the stack
ASarrayPrimes.array = new char[SIZE]; // New character array on the heap
只要确保您释放了 array
内存力也好!更安全的方法是使用 std::vector<char>
或者确实如此。一个std::string
而不是成员(member)char* array
因为它们将为您处理分配/解除分配。
关于c++ - 如何在类中使用数组变量? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12433382/