在成员函数之间传递const变量为数组的索引
Passing const variable between member functions to be index of array
我试图解决这个问题,但是我不能。我有一个类定义,我希望成员函数(SIZ(将常数值返回到另一个成员函数(ABC(。该值在该功能中的数组声明中用作最大索引。但这似乎不起作用。这是一个简化的版本:
class bin {
constexpr int siz();
public:
void abc();
};
constexpr int bin::siz() {
const int sizz = sizeof(int) * 8;
}
void bin::abc() {
char arr[siz()]; // compiler: this expression didn't evaluate as constant (¿?)
};
但是,其他非常相似的代码(但使用简单函数(确实编译了...
constexpr int siz() {
const int sizz = sizeof(int) * 8;
return sizz;
}
int main() {
char arr[siz()];
return 0;
}
我不完全确定,但是我认为问题是在bin::abc
中,该对象可以在运行时是任何东西。因此,bin::siz()
无法在编译时进行评估。
以下工作正常
int main()
{
bin b;
char arr[b.siz()];
}
将bin
更改为:
class bin {
public:
constexpr int siz();
};
constexpr int bin::siz() {
return sizeof(int) * 8;
}
如果siz
不取决于对象的状态,例如在您发布的代码中,我建议将其作为static
成员函数。
以下对我有效。
class bin {
public:
static constexpr int siz();
void abc() const;
};
constexpr int bin::siz() {
return sizeof(int) * 8;
}
void bin::abc() const {
char arr[siz()];
}
int main()
{
bin b;
char arr[b.siz()];
}
相关文章:
- 将数组的地址分配给变量并删除
- 试图让变量检查数组中的某些内容
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 在C++中将变量 wstring 分配给 Char 数组
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- c++ 中的别名变量数组
- 使用类的其他成员变量定义类的成员变量数组
- 可视化 如何在C++中使用复杂变量数组
- 如何 for 循环类变量数组
- 按变量数组中的列将一组整数从文本文件读入
- 运行时C++中的变量数组维度
- C++变量数组
- 将变量(数组类型)从函数传递到"main"范围类型:标准::tr1::match_results<标准::字符串::const_iterator>
- 在堆栈上使用大变量/数组的缺点
- 如何在继承类中创建父类变量数组作为私有成员
- 如何创建一个类变量数组
- 需要以编程方式初始化类变量数组,我怎么做最好
- 直接使用变量(数组中的数据返回相同)或与指针一起使用
- 如何用模板类型初始化成员变量数组