【发布时间】:2013-02-13 02:40:13
【问题描述】:
如果我有一个带有私有变量的类,它应该包含指向另一个类的指针数组,那么下面的语法是否正确?
class MyClass
{
private:
int arraySize;
SomeOtherClass* classPtr[];
}
稍后,当我想在 MyClass 中接受 ifstream、从文件读取并填充数组的函数中为该数组动态分配内存时,我会这样做吗?
void createArray(std::ifstream& fin)
{
//the first int is the array size
fin >> arraySize;
string tempString; //the file is formatted string int string int etc.
int tempInt;
classPtr[arraySize];
for(int i = 0; i < arraySize; i++)
{
fin >> tempString;
fin >> tempInt;
//assume the constructor is defined
classPtr[i] = new SomeOtherClass(tempString, tempInt);
}
提前感谢您的宝贵时间。
【问题讨论】:
-
您似乎不需要数组,为什么要一个?
-
简短的回答是,因为这是作业所要求的。 classPtr 应该跟踪 SomeOtherClass 的多个实例。
-
虽然没有任何东西拼写 array...
-
你永远不能创建一个指向类的指针。
-
也许这是一个糟糕的任务。它声明“创建另一个维护 SomeOtherClass 实例的私有数组的类。” “您将动态分配数组以使其具有确切的大小,然后通过从文件中读取来填充它。”