当前位置:  开发笔记 > 编程语言 > 正文

如何在C++类中创建const数组和计算const值?

如何解决《如何在C++类中创建const数组和计算const值?》经验,为你挑选了1个好方法。

我遇到了一些我不明白的编译器错误.我很确定我在这里做错了但我不知道是什么.我希望将所有世界常量定义为属于该类.

笔记:

我只使用类作为附加成员的结构.我并没有故意遵循严格的面向对象设计.请不要评论公共变量.

我并不太关心编译器内联的东西.我正在使用这种结构,因为我很容易使用它.(如果有效)

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]};

如果可以这样做,那么这样做的正确语法是什么?如果不可能,我应该使用哪种替代方案?



1> Thomas L Hol..:

定义类体外部的静态consts将使用gcc进行编译和执行.

#include 
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;
}

我不能过分强调ebo关于初始化顺序的评论的重要性.


您可能需要解决[静态初始化顺序问题] [1] [1]:http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.13
只要将它们放在同一个文件中,它们就会按顺序初始化.
推荐阅读
mobiledu2402852357
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有