【发布时间】:2023-03-24 03:58:01
【问题描述】:
我已经有一段时间没有使用 c++ 了,但我刚刚开始使用它进行项目。这可能是不可能的,但我试图用一个数组创建一个模板类,该数组将其大小设置为我试图用构造函数设置的常量的值。
这是构造函数的代码:
Tarray(int s): start_size(s){
}
这是设置数组大小的代码:
const int start_size;
T this_array[start_size];
这是整个文件:
#ifndef TARRAY_H_
#define TARRAY_H_
template<typename T>
class Tarray {
private:
const int start_size;
T this_array[start_size];
int array_size;
public:
Tarray(int s): start_size(s){
}
~Tarray(){
delete[] this_array;
}
T & operator[](int i){
return this_array[i];
}
};
#endif /* TARRAY_H_ */
这些是我得到的错误:
..\/template_array/Tarray.h:16:24: error: 'Tarray<T>::start_size' cannot appear in a constant-expression
..\/template_array/Tarray.h:16:34: error: 'new' cannot appear in a constant-expression
..\/template_array/Tarray.h:16:34: error: ISO C++ forbids initialization of member 'this_array' [-fpermissive]
..\/template_array/Tarray.h:16:34: error: making 'this_array' static [-fpermissive]
..\/template_array/Tarray.h: In instantiation of 'Tarray<Person>':
..\Human.cpp:17:24: instantiated from here
..\/template_array/Tarray.h:16:34: error: invalid in-class initialization of static data member of non-integral type 'Person*'
Build error occurred, build is stopped
Time consumed: 343 ms.
当我尝试调整代码时,错误消息一直在发生变化,但这些是来自此特定构建的错误。
感谢您的帮助
【问题讨论】:
-
谢谢,但我仍然想知道你是怎么做到的。好久没用过c++了,想重新学习一下。
-
如果允许这样的构造,
sizeof将如何工作? -
C++ 不支持这种方式的可变长度数组。 C99 有,但 C++ 没有(甚至 C++11 也没有)。 GNU 在 C++ 中支持它们作为扩展,但对于自动变量,而不是类成员(据我所知)。您需要显式使用
new/malloc,或使用vector并让该类为您管理动态分配(几乎在所有情况下都是更好的方法)。 -
如果该值仅在运行时已知,则必须使用 new 动态分配数组。如果值在编译时已知,则可以是模板参数,模板参数可用于数组大小。
-
我认为 C99 也不支持它作为结构的一部分,因此这些限制同样适用于 C99 和 C++-with-gnu-extensions。
标签: c++ arrays class constructor constants