构造函数中的常量数组初始化 [英] constant array initialization in constructor

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

问题描述

我每个人,

常量数组必须在声明时初始化.但是,如果数组在类中声明,该怎么办?我一直在搜索,但到目前为止仍未找到解决方案,有人知道吗?
示例:

I everyone,

Constant arrays must be initialized at declaration. But what if the array is declared in a class? I''ve been searching but didn''t find a solution so far, does anybody know?
Example:

template <class t=""> class Foo
{
const T vec[10];
};


推荐答案

在C ++ 98中,您不能.但是,如果您深入研究C ++的黑暗历史以及C的传统,那么您可以.解决这个问题的事实是,如果数组是另一个结构或类的一部分,则在复制结构时,它会与其他所有内容一起被复制.因此,如果有人告诉您不能按值返回数组,请告诉他们您当然可以:
In C++98 you can''t. But if you dig into the murky past of C++ and it''s C heritage then you can. The thing that gets around this is the fact that if an array is part of another structure or class it gets copied along with everything else when the structure is copied. So if anyone tells you that you can''t return an array by value, tell them of course you can:
struct B
{
    int data[15];
};

B grab_a_B()
{
    B b;
    b.data[0] = 125;
    // and so on...
    return b;
};

那么,这对您有什么帮助?好吧,不要在您的类中使用const数组,而应使用结构的const实例:

So how does this help you? Well instead of using a const array in your class, use a const instance of a structure instead:

class A
{
    public:
        A( const B &b ) : b_( b ) {}

    private:
        const B b_;
};

初始化B,然后将其喂给A,然后剪断,剪断Bob的阿姨.

在C ++ 11中,有一项功能(统一初始化)可用于执行相同的操作.因此,您可以执行以下操作:

Initialise a B, feed it to an A and snip, snip, Bob''s yer aunty.

In C++11 there is a feature (uniform initialisation) that you can use to do the same thing. So you can do something like:

class A
{
    public:
        A(): arr( {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15} ) {}
    private:
        const int arr[ 15 ];
};

尽管语法来自内存. Visual Studio直到2010年都不支持此功能,我不确定gcc是否也支持gcc.

although the syntax is from memory. Visual Studio up ''til 2010 doesn''t support this, I''m not sure about gcc whether gcc does either.


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

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