第一维未大小类成员

First Dimension Unsized Class Member

本文关键字:小类 成员 一维      更新时间:2023-10-16

我有一个我要转换的类:

class MyClass
{
public::
    void foo( void )
    {
        static const char* bar[][3] = { NULL };
        func( bar );
    }
};

现在我想让bar成为一个成员变量,但是因为第一个维度是unsize的,所以我不能。我也不能把const char** bar[3]传给void func( const char* param[][3] )。是否有我不知道的解决方法,或者这是我必须使用static方法的情况?

编辑响应Jarod42

匹配bar的初始化是我这里的问题。我想我至少应该能够在函数体中完成这个,如果不是在函数初始化列表中。下面是一些测试代码:

static const char* global[][3] = { NULL };
void isLocal( const char* test[][3] )
{
    // This method outputs" coolncoolnuncooln
    if( test == NULL )
    {
        cout << "uncool" << endl;
    }
    else if( *test[0] == NULL )
    {
        cout << "cool" << endl;
    }
}
class parent
{
public:
    virtual void foo( void ) = 0;
};
parent* babyMaker( void )
{
    class child : public parent
    {
    public:
        virtual void foo( void )
        {
            static const char* local[][3] = { NULL };
            isLocal( local );
            isLocal( global );
            isLocal( national );
        }
        child():national( nullptr ){}
    private:
        const char* (*national)[3];
    };
    return new child;
}
int main( void )
{
    parent* first = babyMaker();
    first->foo();
}

const char* bar[][3]不是const char** bar[3]而是const char* (*bar)[3]
所以你可能想要这样写:

class MyClass
{
public:
    MyClass() : bar(nullptr) {}
    void foo() { func(bar); }
private:
    const char* (*bar)[3];
};

我建议使用typedef作为:

class MyClass
{
public:
    typedef const char* bar_t[3];
public:
    MyClass() : bar(new bar_t[2]) {
        for (int j = 0; j != 2; ++j) {
            for (int i = 0; i != 3; ++i) {
                bar[j][i] = nullptr;
            }
        }
    }
    ~MyClass() { delete [] bar; }
    void foo() { func(bar); }
private:
    MyClass(const MyClass&); // rule of three
    MyClass& operator =(const MyClass&); // rule of three
private:
    bar_t* bar;
};

或:

class MyClass
{
public:
    typedef const char* bar_t[3];
public:
    MyClass() { for (int i = 0; i != 3; ++i) { bar[0][i] = nullptr; } }
    void foo() { func(bar); }
private:
    bar_t bar[1];
};