【发布时间】:2015-02-07 22:28:26
【问题描述】:
我正在尝试编写一个 C++ 程序来解决魔方问题。我定义了四个类:Piece、Edge、Corner 和 Cube,其中 Corner 和 Edge 是 Piece 的子类。
Cube 类是这样定义的:
class Cube{
private:
Piece* pieces[3][3][3];
public:
Corner* WRG = new Corner(WHITE, RED, GREEN, WHITE);
Corner* WGO = new Corner(WHITE, GREEN, ORANGE, WHITE);
Corner* WOB = new Corner(WHITE, ORANGE, BLUE, WHITE);
Corner* WBR = new Corner(WHITE, BLUE, RED, WHITE);
Corner* YRB = new Corner(YELLOW, RED, BLUE, YELLOW);
Corner* YBO = new Corner(YELLOW, BLUE, ORANGE, YELLOW);
Corner* YOG = new Corner(YELLOW, ORANGE, GREEN, YELLOW);
Corner* YGR = new Corner(YELLOW, GREEN, RED, YELLOW);
Edge* WR = new Edge(WHITE, RED, WHITE);
Edge* WB = new Edge(WHITE, BLUE, WHITE);
Edge* WO = new Edge(WHITE, ORANGE, WHITE);
Edge* WG = new Edge(WHITE, GREEN, WHITE);
Edge* YR = new Edge(YELLOW, RED, YELLOW);
Edge* YB = new Edge(YELLOW, BLUE, YELLOW);
Edge* YO = new Edge(YELLOW, ORANGE, YELLOW);
Edge* YG = new Edge(YELLOW, GREEN, YELLOW);
Edge* GO = new Edge(GREEN, ORANGE, GREEN);
Edge* GR = new Edge(GREEN, RED, GREEN);
Edge* BO = new Edge(BLUE, ORANGE, BLUE);
Edge* BR = new Edge(BLUE, RED, BLUE);
Cube();
~Cube();
void rotateRedClock();
void rotateRedCounter();
void rotateOrangeClock();
void rotateOrangeCounter();
void rotateYellowClock();
void rotateYellowCounter();
void rotateGreenClock();
void rotateGreenCounter();
void rotateBlueClock();
void rotateBlueCounter();
void rotateWhiteClock();
void rotateWhiteCounter();
void doMove(int);
Piece getPieces();
Cube* getChildren();
};
Cube::Cube(){
Piece* pieces[3][3][3] = { { { WRG, WR, WBR }, { GR, NULL, BR }, { YGR, YR, YRB } }, //Red face
{ { WG, NULL, WB }, { NULL, NULL, NULL }, { YG, NULL, YB } }, //Middle section
{ { WGO, WO, WOB }, { GO, NULL, BO }, { YOG, YO, YBO } } }; //Orange face
}
这个数组存储在一个 Cube 对象中,该对象可以打乱数组中的指针并更改每个 Piece 的方向参数以处理旋转。据我所知,这一切都应该可以正常工作。
当我尝试返回包含当前状态下所有可能移动的 Cube 对象数组时,问题就开始了。
如果我用 Java 编程,它看起来像这样:
public Cube[] getChildren(){
Cube children = new Cube[12];
for (int i = 0; i < 12; i++){
children[i] = new Cube(this.getPieces()); //Effectively clone this
children[i].doMove(i); //Does one of the 12 available moves on the cube
}
return children;
}
然而,在 C++ 中,我似乎无法实现这个目标。我尝试了以下方法:
Cube* Cube::getChildren(){
Cube* children = new Cube[12];
for (int i = 0; i < 12; i++){
children[i] = Cube();
children[i].pieces = pieces;
children[i].doMove(i);
}
return children;
}
但我在这一行得到一个错误:
children[i].pieces = pieces;
上面写着:
error C2106: '=' : left operand must be l-value
我是 C++ 新手,这个错误可能是由于我对某些概念缺乏了解造成的。我想知道我做错了什么,以便将来避免此类问题。提前致谢!
【问题讨论】:
-
什么是
Cube::pieces?请出示其声明。 -
发布
Cube的类定义以获得更好的帮助 -
Cube 的定义不是必须的,因为已经显示了 Cube::pieces 的定义。不幸的是,在所有无关紧要的混乱中很容易错过它。
-
如果
Piece实际上是一个类,则显示其定义以及WRG, WR, WBR等的定义。 -
在你的构造函数中,
Piece* pieces[3][3][3]是一个新变量,它不引用类成员pieces
标签: c++ arrays pointers lvalue