第一维超大型班级成员 [英] First Dimension Unsized Class Member
问题描述
我有一个要转换的课程:
I have a class I'm converting:
class MyClass
{
public::
void foo( void )
{
static const char* bar[][3] = { NULL };
func( bar );
}
};
现在我想将bar设置为成员变量,但是由于第一个维度的大小我无法。我也无法将 const char ** bar [3]
传递给 void func(const char * param [] [3])
。是否有我不知道的解决方法,还是这种情况我必须使用 static
方法?
Now I want to make bar a member variable, but because the first dimension is unsized I can't. I also can't pass const char** bar[3]
to void func( const char* param[][3] )
. Is there a workaround for this that I'm unaware of, or is this a situation where I must use a method static
?
编辑以响应 Jarod42
Edit in Response to Jarod42
匹配 bar
的初始化是我的问题。我认为,如果没有ctor初始化列表,我至少应该能够在ctor主体中完成此操作。这里是一些测试代码:
Matching the initialization of bar
is my problem here. I think I should at least be able to accomplish this in the ctor body, if not the ctor initialization list. Here's some test code:
static const char* global[][3] = { NULL };
void isLocal( const char* test[][3] )
{
// This method outputs" cool\ncool\nuncool\n
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]
。
所以您可能想要以下内容:
const char* bar[][3]
is not const char** bar[3]
but const char* (*bar)[3]
.
So you may want something like:
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];
};
这篇关于第一维超大型班级成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!