【发布时间】:2021-07-03 23:18:20
【问题描述】:
我在尝试获取数组的 typeid 时遇到问题。当我输入 typeid(*ptr[0]).name() 时,它工作得非常好。但是一旦我将 0 更改为循环中的变量,它就会给我这个错误,请帮助我!
#include "Cellphone.h"
#include "Electronic_device.h"
#include "Laptop.h"
#include "Smartwatch.h"
#include <vector>
#include <typeinfo>
int main()
{
string name;
int i = 0;
Electronic_device** ptr = new Electronic_device*[100];
Cellphone c1("Samsung", 1023, "black", 250.00, 1);
Smartwatch s1("IBM", 10, "red", 350.00, 2);
Laptop l1("HP", 102, "black", 1250.00, 16, true);
ptr[0] = &c1;
ptr[1] = &s1;
ptr[2] = &l1;
ptr[0]->print();
for (i = 0; i < sizeof(ptr); i++)
{
if (typeid(*ptr[i]) == typeid(Cellphone))
{
cout << "Cellphone" << endl;
}
if (typeid(*ptr[i]) == typeid(Smartwatch))
{
cout << "Smartwatch" << endl;
}
if (typeid(*ptr[i]) == typeid(Laptop))
{
cout << "Laptop" << endl;
}
}
((Cellphone *)ptr[0])->printCellphone();
}
【问题讨论】:
-
0xCDCDCDCD我们常用的memory bit pattern 用于未初始化的堆分配内存。 -
sizeof(ptr)将是 4 或 8,即 32 或 64 位,而不是 100。在两个位置使用相同的常量。 -
关于您的问题的一个重要提示:
sizeof(ptr)是 指针ptr的大小(以 字节 为单位),而不是数量它可能指向的任何可能数组的元素。并不是说即使是这样也可以,因为您没有初始化数组的所有元素。请改用std::vector<Electronic_device*>!而且typeid(*ptr[i]) == typeid(Cellphone)不行,最好改用多态和虚函数。 -
sizeof(ptr) 不会告诉你数组有多大,它会告诉你指针的大小(以字节为单位)
-
一般来说,当您看到一个非常重复的数字或看起来有点像单词或短语的数字时,很有可能程序试图告诉您一些事情,您应该查找该数字。当你得到一个奇怪的十进制数字时,把它变成十六进制,看看它是否更容易识别/重复。
标签: c++