在类中初始化固定大小的常量数组 [英] Initializing constant array of fixed size inside class

查看:175
本文介绍了在类中初始化固定大小的常量数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的类:

class A {
    const int arr[2];
public:
      A() { }
};

是否可以初始化 arr const int arr [2] = {1,2}; )?)

Is it possible to initialize arr from the constructor initializer list or in any other way than on the line where it is declared (i.e. const int arr[2] = {1,2};)?

注意,我对使用C ++ 98的方法感兴趣。

Note that I'm interested in methods that work with C++98!

推荐答案

将它们包装在 struct 中,例如:

By wrapping them in a struct, e.g.:

class A
{
    struct Data
    {
        int arr[2];
    };

    Data const arr;
public:
    A() : arr( someOtherStruct ) {}
};

这意味着要访问数据,你必须写 arr.arr
通过继承 struct 可以避免这种情况:

This does mean that to access the data, you'd have to write arr.arr. It's possible to avoid that by inheriting from the struct:

struct PrivateDataForA
{
    int arr[2];
};

class A : private PrivateDataForA
{
public:
    A() : PrivateDataForA( someOtherStruct ) {}
};

这使得 struct 可见外部类
(这可能是一个优势—客户端代码可以传递一个作为
参数)。

This does make the name of the struct visible outside of the class (which might be an advantage—client code could pass you one as an argument).

t有一个struct的实例,因为你想要
填充从构造函数的参数计算的值,你
可以使用一个静态成员函数:

If you don't have an instance of the struct handy, say because you want to fill it with values calculated from arguments to the constructor, you can use a static member function:

class A : private PrivateDataForA
{
    static PrivateDataForA createInitializer( int a, int b );
public:
    A( int a, int b ) : PrivateDataForA( createInitializer( a, b ) )
    {
    }
};






有关具体示例: p>


For the OP’s concrete example:

#include <iostream>
#include <stddef.h>

typedef ptrdiff_t   Size;
typedef Size        Index;

template< class Element, Size n >
struct Array{ Element elem[n]; };

class A {
    Array<int, 2> const arr_;       // const int arr[2];

    A& operator=( A const& );       // No such.

    static Array<int, 2> const& oneAndTwo()
    {
        static Array<int, 2> const a = {1, 2};
        return a;
    }

public:
    A(): arr_( oneAndTwo() ) {}
    int at( Index i ) const { return arr_.elem[i]; }
};


int main()
{
    using namespace std;

    A o;
    for( int i = 0;  i < 2;  ++i )
    {
        cout << o.at( i ) << endl;
    }
}

这篇关于在类中初始化固定大小的常量数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆