C ++:如何为具有多个const成员的类定义一个构造函数,其中一个是数组?

问题描述 投票:-1回答:1

我有一个包含三个const成员的类,其中一个是数组。我试图定义一个构造函数来初始化那些const成员,因为出于我的目的它们不能被硬编码。但是,当我包含数组成员时,尝试定义构造函数的任何方式都会引发错误。这是我目前拥有的:

class c
{
    enum e{first, second, third, fourth, fifth, sixth};
    public:
        ctor();
        ctor(e aDef, int bDef, int cDef[]): a(aDef), b(bDef), c(coordsDef[]){}

    private:
        const e a;
        const int b;
        const int c[2];

};

这是我得到的错误:

error: expected primary-expression before ']' token|

有人可以解释我的错误之处吗?

c++ constructor initialization const member
1个回答
0
投票

您的类名称必须与您的ctor名称相同,并且您已经声明了默认ctor且尚未定义它,并且无法像您那样初始化静态数组,请使用类似以下的内容

class c
{
public:
    enum e{first, second, third, fourth, fifth, sixth};
    c() = default;
    c(e aDef, int bDef, int (&cArrDef)[2]): a(aDef), b(bDef), cArr(cArrDef){}

private:
    const e a;
    const int b;
    const int * const cArr ;

};

int main(){
    int arr[] = {1,2};
    c instant = c{c::e::first, 1, arr};

}

注意,要使用嵌套类,必须将其公开

© www.soinside.com 2019 - 2024. All rights reserved.