How to declare a constant array in class with cons

2019-07-03 15:02发布

How to declare a constant array in class with constant class variable? Is it possible. I don't want dynamic array.

I mean something like this:

class test
{
    const int size;
    int array[size];
    public:
    test():size(50)
    {}
}

int main()
{
    test t(500);
    return 0;
}

the above code gives errors

3条回答
smile是对你的礼貌
2楼-- · 2019-07-03 15:11

You mean a fixed sized array? You could use std::array like this:

#include <array>

class test
{
    static const size_t s_size = 50;
    std::array<int, s_size>   m_array;
public:
    test()
    {
    }
};

Or if you want to support different sizes you need to resort to a class template like this:

#include <array>

template <size_t SIZE>
class test
{
    std::array<int, SIZE>   m_array;
public:
    test()
    {
    }
};

std:array has the added benefit of keeping the size information along with the member (unlike arrays which decay to pointers) and is compatible with the standard library algorithms.

There is also a version that Boost offers (boost::array) which is similar.

查看更多
贼婆χ
3楼-- · 2019-07-03 15:15

No, it's not possible: As long as size is a dynamic variable, array[size] cannot possibly be implemented as a static array.

If you like, think about it this way: sizeof(test) must be known at compile time (e.g. consider arrays of test). But sizeof(test) == sizeof(int) * (1 + size) in your hypothetical example, which isn't a compile-time known value!

You can make size into a template parameter; that's about the only solution:

template <unsigned int N>
class Test
{
  int array[N];
  static const unsigned int size = N; // unnecessary really
public:
  // ...
};

Usage: Test<50> x;

Note that now we have sizeof(Test<N>) == sizeof(int) * (1 + N), which is in fact a compile-time known value, because for each N, Test<N> is a distinct type.

查看更多
\"骚年 ilove
4楼-- · 2019-07-03 15:15

Your code yields an error because compiler needs to know the size of data type of each member. When you write int arr[N] type of member arr is "an array of N integers" where N must be known number in compile time.

One solution is using enum:

class test
{
    enum 
    {
        size = 50
    };

    int arr[size];
   public:
    test() {}
};

Another is declaring size as static const member of class:

class test
{
    static const int size = 50; 
    int arr[size];
   public:
    test(){}
};

Note that in-class initialization is allowed only for static class integers! For other types you need to initialize them in code file.

查看更多
登录 后发表回答