为什么使用"typeid"时必须输入数组的长度?
Why do I have to enter length of array while using "typeid"?
我正在学习c++11,虽然我想测试typeid
语法,但我不明白为什么我必须输入数组的长度才能识别它
例如:
char name[9];
if (typeid(name) == typeid(char []) // without length
cout<<"Okay"<<endl; // not print
char name[9];
if (typeid(name) == typeid(char [9]) // with length
cout<<"Okay"<<endl; // okay
但如果我不写length9
,它就不起作用,我必须输入ength9
。为什么
因此:
if (typeid(name) == typeid(char)) // only char wrong | ok | logical
if (typeid(name) == typeid(char *)) // by * wrong | ok | logical
if (typeid(name) == typeid(char [])) // onle [] wrong | don't understand
if (typeid(name) == typeid(char [9])) // okay | but why ?
我希望typeid(char[])
能起作用。实际上数组的长度是多少?
char[2]
不是char[3]
。它们是完全分离的类型。元素的数目不仅仅是一个参数。它是类型本身的一部分。
您可以考虑元素的数量如下:
template <class T, size_t N>
class array{
public:
T[N] data;
}
如果你想使用这个类,你应该写:
array<int,6> foo;
array<int,7> bar;
在编译时,数组类型将被转换为如下类型:
array_int_6 foo;
array_int_7 bar;
CCD_ 7。从而导致:typeid(foo) != typeid(bar)
和typeid(array<int,6>) != typeid(array<int,7>)
数组的大小是其类型的一部分。char[7]
与char[8]
不是一回事。我们可以用证明这一点
void foo(char (&arr)[6]) {}
现在使用该函数,我们只能传递类型为char[6]
的数组。看看这个例子,你可以看到编译器会抱怨数组与函数中指定的大小不匹配。
相关文章:
- 检查TCHAR数组输入是否为带符号整数C++
- C++数组输入不接受一定数量的整数
- 为什么我的代码无法处理大型数组输入(>10000)?
- 我正在努力处理多维数组输入和输出,我管理输入,但是打印无法按计划工作
- 使用无符号字符数组输入十六进制数
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 如何从用户获取数组输入
- C 2x2数组输入线
- 字符数组输入限制
- 将字符串数组输入到函数C++
- C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题
- 数组排序、数组输入、数组输出
- 将字符数组输入stdin
- 如何在 c++ 中为对象数组输入字符串
- 如何在c++ mex文件中访问多维数组输入
- 读取文件并将其作为整型数组输入
- 从c++文件中获取输入(矩阵数组输入)
- 数组输入不工作
- 函数结构数组输入cin问题
- 结束数组输入(c++行业标准)