我希望外部类中有一个数组,内部类中的变量就是数组的大小:
struct Outer
{
struct Inner
{
int size{};
int something_else{};
};
Inner inner;
int data[size]; // size is not declared in Outer, hence compiler give an error
};我怎么能做这种事?
发布于 2021-07-12 07:20:29
由于inner是在data之前定义的,因此初始化工作非常好:
struct Outer
{
struct Inner
{
int size{};
int something_else{};
};
Inner inner;
std::vector<int> data;
Outer() : Inner(), data(inner.size) { }
};是的,struct也可以有一个构造函数。只是一个默认的公共课程。
发布于 2021-07-12 07:15:11
struct Outer
{
struct Inner
{
int m_size{};
int something_else{};
Inner(int size) :m_size(size)
{
}
};
Inner inner{ 5 };
int* data = new int[inner.m_size];
};
int main()
{
Outer outer;
for (int i = 0; i < outer.inner.m_size; ++i)
{
std::cout << outer.data[i] << std::endl;
}
}不应公开大小变量,因为在创建对象后,大小变量的更改不会更改数组的大小。
发布于 2021-07-12 06:51:34
变量size尚未声明,您正在尝试访问不存在的内存块
假设您的需求不需要精确的大小,我建议考虑以下选项
声明一个宏
#DEFINE size n其中n=你喜欢的尺寸
动态内存分配
Inner* inner= malloc(size * sizeof *inner); //Where size = your specified sizehttps://stackoverflow.com/questions/68342846
复制相似问题