在没有#define的头文件中声明数组大小

时间:2020-12-27 21:43:02

I have a code a following (simplified version):

我有一个代码(简化版):

#define MESSAGE_SIZE_MAX 1024
#defined MESSAGE_COUNT_MAX 20

class MyClass {
public:
   .. some stuff
private:
   unsigned char m_messageStorage[MESSAGE_COUNT_MAX*MESSAGE_SIZE_MAX];
};

I don't like defines, which are visible to all users of MyCalss.

我不喜欢定义,它们对MyCalss的所有用户都是可见的。

How can I do it in C++ style?

我怎么能用C ++风格呢?

Thanks Dima

2 个解决方案

#1


The trick to get such things into the class definition is,

将这些东西纳入类定义的技巧是,

// public:
enum {MESSAGE_SIZE_MAX=1024, MESSAGE_COUNT_MAX=20};

I never liked #defines to be used like constants.
Its always a good practice to use enum.

我从不喜欢#defines像常量一样使用。使用枚举总是一个很好的做法。

#2


Why don't you simply use a constant?

你为什么不简单地使用常数?

const int message_size_max = 1024;

Note that unlike C, C++ makes constant variables in global scope have static linkage by default.

请注意,与C不同,C ++使得全局范围内的常量变量默认具有静态链接。

The constant variable above is a constant expression and as such can be used to specify array sizes.

上面的常量变量是常量表达式,因此可用于指定数组大小。

char message[message_size_max];

#1


The trick to get such things into the class definition is,

将这些东西纳入类定义的技巧是,

// public:
enum {MESSAGE_SIZE_MAX=1024, MESSAGE_COUNT_MAX=20};

I never liked #defines to be used like constants.
Its always a good practice to use enum.

我从不喜欢#defines像常量一样使用。使用枚举总是一个很好的做法。

#2


Why don't you simply use a constant?

你为什么不简单地使用常数?

const int message_size_max = 1024;

Note that unlike C, C++ makes constant variables in global scope have static linkage by default.

请注意,与C不同,C ++使得全局范围内的常量变量默认具有静态链接。

The constant variable above is a constant expression and as such can be used to specify array sizes.

上面的常量变量是常量表达式,因此可用于指定数组大小。

char message[message_size_max];