本文介绍了使用静态const + const作为数组绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做类似的事情



Class.hpp:

  class Class {

private:
static const unsigned int arraySize;
int ar [arraySize + 2];
};

Class.cpp:

  #include< Class.hpp> 
const unsigned int arraySize = 384;

编译器(q ++,用于基于g ++的QNX OS的c ++编译器)给我错误:在编译包含 Class.hpp 的单元时(不是在编译Class.cpp时),数组绑定不是整数常量。 / p>

为什么这样不起作用?我知道静态的const成员可以用作数组绑定,这由C ++标准保证(请参阅)。但是,为什么编译器不将 static const + const 的结果视为常量?

解决方案

这是应该由编译器接受的良好代码:

  class Class {
const static int arraySize = 384;
int ar [arraySize + 2];
};

,如果不是,则说明编译器已损坏。



但是,如果将实际常量从头文件移出到选定的翻译单元,则会使代码无效。

  // Class.h 
class Class {
const static int arraySize;
int ar [arraySize + 2]; //错误
};

// Class.cpp
const int Class :: arraySize = 384;

这是因为班级的规模在编译时无法仅根据头文件中的可用数据来确定对象。这不是完全正确的原因,但是按照这些思路进行推理有助于理解诸如此类的编译错误。



为避免发生此类错误,您可以可以用 enum 代替 static const int ,例如

  class类{
枚举{arraySize = 384};
int ar [arraySize + 2];
};


I'm doing something like this

Class.hpp:

 class Class {

 private:
     static const unsigned int arraySize;
     int ar[arraySize+2];
 };

Class.cpp:

#include <Class.hpp>
const unsigned int arraySize = 384;

The compiler (q++, a c++ compiler for the QNX OS based on g++) gives me error: array bound is not an integer constant while compiling a unit including Class.hpp (not while compiling Class.cpp).

Why isn't that working? I know that a static const member can be used as an array bound, guaranteed by the C++ standard (see this anwser). But why doesn't the compiler see the result of static const + const as a constant?

解决方案

This is good code which should have been accepted by the compiler:

class Class {
  const static int arraySize = 384;
  int ar[arraySize+2];
};

and if it isn't, your compiler is broken.

However, if you move actual constant out of the header file to selected translation unit, that invalidates the code.

// Class.h
class Class {
  const static int arraySize;
  int ar[arraySize+2]; // ERROR
};

// Class.cpp
const int Class::arraySize = 384;

This is because the size of your Class object cannot be determined at compile time from the data available in the header alone. This is not exactly right reason, but reasoning along these lines helps to understand compilation errors such as this.

To avoid making such mistakes, you can replace static const int with an enum, e.g.

class Class {
  enum { arraySize = 384 };
  int ar[arraySize+2];
};

这篇关于使用静态const + const作为数组绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 21:24