我遇到了一些我不明白的编译器错误.我很确定我在这里做错了但我不知道是什么.我希望将所有世界常量定义为属于该类.
笔记:
我只使用类作为附加成员的结构.我并没有故意遵循严格的面向对象设计.请不要评论公共变量.
我并不太关心编译器内联的东西.我正在使用这种结构,因为我很容易使用它.(如果有效)
class Board{
public:
enum PhysicsResult{ BOUNCE, OUT_OF_BOUNDS_TOP, OUT_OF_BOUNDS_BOTTOM, CONTINUE };
//World constants
const static float Height = 500;
const static float Width = 300;
//ERROR: 'Board::Width' cannot appear in a constant-expression.
const static float PaddleWidth = Width/15;
const static float BallRadius = 5;
const static float BounceDistance = 1.5;
//World Objects
Ball ball;
Paddle paddle1;
Paddle paddle2;
/*
1---2
| |
0---3
*/
//ERROR: a brace-enclosed initalizer is not allowed here before '{' token
//ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[4]'
const static Pair corners[4] = {Pair(0, 0), Pair(0, Height), Pair(Width, Height), Pair(Width, 0)};
//ERROR: a brace-enclosed initalizer is not allowed here before '{' token
//ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]'
const static Pair left_wall[2] = {corners[0], corners[1]};
//ERROR: a brace-enclosed initalizer is not allowed here before '{' token
//ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]'
const static Pair right_wall[2] = {corners[3], corners[2]};
//ERROR: a brace-enclosed initalizer is not allowed here before '{' token
//ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]'
const static Pair top_wall[2] = {corners[1], corners[2]};
//ERROR: a brace-enclosed initalizer is not allowed here before '{' token
//ERROR: invalid in-class initalization of static data member of nonintegral type 'const Pair[2]'
const static Pair bottom_wall[2] = {corners[0], corners[3]};
Run Code Online (Sandbox Code Playgroud)
如果可以这样做,那么这样做的正确语法是什么?如果不可能,我应该使用哪种替代方案?
定义类体外部的静态consts将使用gcc进行编译和执行.
#include <iostream>
using namespace std;
struct Pair { int a; int b; Pair(int x, int y) : a(x),b(y) {}};
struct F {
static const float blah = 200.0;
static const Pair corners[4];
};
// square boards are so ordinary
const Pair F::corners[4] = { Pair(0,0), Pair(0,1), Pair(2,0), Pair(2,2) };
const float F::blah ;
int main(int, char **) {
cout << F::corners[0].a << endl ;
cout << F::blah << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我不能过分强调ebo关于初始化顺序的评论的重要性.
归档时间: |
|
查看次数: |
504 次 |
最近记录: |