第一维未大小类成员
First Dimension Unsized Class Member
我有一个我要转换的类:
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];
};
相关文章:
- 将函数类成员映射到类本身内部
- 将Ref对象作为类成员
- 如何使用基类指针引用派生类成员
- g++ 在某个类成员未初始化时不发出警告
- 是否可以同时声明一个类成员的常量/非常量?
- 将自由函数绑定为类成员函数
- 访问类成员而不复制此变量或互斥变量
- 访问条件类成员的方法不仅在被调用时才编译
- 类成员和中断
- 类的前向声明之后的类成员函数定义,在类声明之前
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- std::ofstream 作为类成员删除复制构造函数?
- 删除C++继承中虚拟类成员的代码重复
- 现代 C++ 中作为类成员的非拥有指针
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- C++初始化类实例时隐式调用类成员的构造函数
- 在运行时为随机分布类成员设置最小和最大边界?
- 为什么要返回对小类成员的 const 引用?
- 我看到将我的类成员函数指定为内联实际上会增加执行时间,即使函数体非常小
- C 类的设计:其他类成员中类成员的共同用途;小界面与小课