【发布时间】:2014-10-23 18:52:14
【问题描述】:
我使用 c++11。我正在尝试初始化一个多维数组。第一次尝试是
const static int COORDINATES[4][4][2]={{{-1,-1},{0,0},{1,1},{2,0}},
{{-1,1},{0,0},{1,-1},{0,-2}},
{{1,1},{0,0},{-1,-1},{-2,0}},
{{1,-1},{0,0},{-1,1},{0,2}}};
编译器抱怨 constexpr,所以我写了
constexpr const static int COORDINATES[4][4][2]={{{-1,-1},{0,0},{1,1},{2,0}},
{{-1,1},{0,0},{1,-1},{0,-2}},
{{1,1},{0,0},{-1,-1},{-2,0}},
{{1,-1},{0,0},{-1,1},{0,2}}};
没有错误,但是当我在方法中使用数组时,会出错。没看懂……
void LShape::rotateShape(Square* cloneSquares) {
int var=COORDINATES[1][1][1]; //no problems
int x=2;
var=COORDINATES[0][x][0]; //error 'not defined' because of x
//if changed to number, works
}
错误:
LShape.cpp:23: referencia a `LShape::COORDINATES' sin definir //reference to L...S not defined
第 23 行是 COORDINATES 的第二次使用
我的完整代码,LShape 标头
#ifndef LSHAPE_H
#define LSHAPE_H
#include "Square.h"
#include "EmptySquare.h"
#include "Shape.h"
class LShape : public Shape {
public:
LShape();
LShape(const LShape& orig);
virtual ~LShape();
inline int getState() {return state;}
inline int getNUMBER_OF_STATES() {return NUMBER_OF_STATES;}
inline int getNUMBER_OF_SQUARES() {return NUMBER_OF_SQUARES;}
void rotateShape(Square* cloneSquares);
private:
int state;
static const int NUMBER_OF_STATES=4;
static const int NUMBER_OF_SQUARES=4;
constexpr const static int INITIAL_COORDINATES[3][2]={{1,0},{1,0},{1,1}};
constexpr const static int COORDINATES[4][4][2]={{{-1,-1},{0,0},{1,1},{2,0}},
{{-1,1},{0,0},{1,-1},{0,-2}},
{{1,1},{0,0},{-1,-1},{-2,0}},
{{1,-1},{0,0},{-1,1},{0,2}}};
};
#endif /* LSHAPE_H */
L形状代码
#include "../../include/LShape.h"
LShape::LShape() : Shape(){
//numberSquares=4;
//squares = new Square[numberSquares];
}
LShape::~LShape(){
//dtor
}
LShape::LShape(const LShape& other){
//copy ctor
}
void LShape::rotateShape(Square* cloneSquares) {
int var=COORDINATES[1][1][1]; //no problems
int x=2;
var=COORDINATES[0][x][0]; //error not defined
}
顺便说一句,我是 C++ 的新手,不要对我不好 :)
编辑:我在 linux (GCC) 中使用默认编译器,IDE 使用以下命令
g++ -std=c++11 -c -g -MMD -MP -MF "build/Debug/GNU-Linux-x86/src/shape/LShape.o.d" -o build/Debug/GNU-Linux-x86/src/shape/LShape.o src/shape/LShape.cpp
【问题讨论】:
-
在定义坐标之前包含 shape.h !
-
@Christophe 我看不出有什么问题...坐标仅在 LShape 中,而不是形状
-
@Piotr S. 我在 linux (GCC) 中使用默认编译器,IDE 使用以下命令 g++ -std=c++11 -c -g -MMD -MP -MF " build/Debug/GNU-Linux-x86/src/shape/LShape.od" -o build/Debug/GNU-Linux-x86/src/shape/LShape.o src/shape/LShape.cpp
标签: c++ arrays c++11 constexpr