我已经看到这个问题已被提出但不完全是从这种方法。我查看了其他线程,并没有看到我必须采取的方法的解决方案。请提前原谅我这篇冗长的帖子。 我必须从OOP角度解决这个问题,我正在尝试使用数组来保存用户输入的磁盘数量。我没有看到另一种做法。
**This is my .h file for the class Tower.**
#include <iostream>
#include <string>
#include "Location.h"
using namespace std;
//Class for the tower
class Tower
{
private:
Location _location;
public:
//Constructor to build object
Tower(Location location);
//set get functions to set and get values.
void setLocation (Location newLocation);
Location getLocation()const;
};
**This is my location.h file i used an enum datatype to specify the location of each peg.**
enum Location
{
start,
middle,
last
};
**My disk.h file that has the properties of my disks.**
using namespace std;
class Disk
{
private:
int _diskLocation;
int _diskSize;
public:
Disk(Tower tow1, int sizeOfDisk);
void setdiskSize(int);
int getdiskSize()const;
void setdiskLocation(Tower newTower);
Tower getdiskLocation()const;
};
**This is my implementation file where I initialized the constructor and its data members.**
using namespace std;
Tower::Tower(Location location)
{
setLocation(location);
}
Disk::Disk(Tower tow1, int sizeOfDisk)
{
setdiskSize(sizeOfDisk);
setdiskLocation(tow1);
}
Finally the main.cpp file. here i make the objects to be used but when i try to pass in the number of disks entered by the user into the array i get the following error. **"Array initializer must be an initializer list"**
int main(int argc, const char * argv[])
{
Tower tower1(start);
Tower tower2(middle);
Tower tower3(last);
int numberOfDisks =0;
cout << "Enter number of disks: " << endl;
cin >> numberOfDisks;
Disk disks[] = new Disk [numberOfDisks]
return 0;
}
我开始认为使用这种方法无法解决问题。我在互联网上发现的这个问题的每个解决方案都是在程序上完成的。除了一些其他语言和编程概念,我还没有被教过。这是我参加过的第二个编程课程。谢谢你的帮助。
答案 0 :(得分:0)
Disk disks[]
和Disk* disks
之间存在差异。您可以执行Disk* disks = new Disk[numberOfDisks];
(请注意您的示例中缺少的;
),但您无法执行Disk disks[] = new Disk[numberOfDisks];
。请参阅this post以了解原因。