【发布时间】:2019-04-08 12:03:38
【问题描述】:
为什么任何指针的大小都是 4 或 8 字节,但它不能容纳任何不同的变量?尝试为双指针分配 int 指针值时出错。
int *int_ptr{nullptr};
float *float_ptr{nullptr};
double *double_ptr{nullptr};
long double *long_double_ptr{nullptr};
string *string_ptr{nullptr};
vector<int> *vector_ptr{nullptr};
cout << "sizeof int pointer is " << sizeof int_ptr; //8 or 4
cout << "sizeof float pointer is " << sizeof float_ptr; //8 or 4
cout << "sizeof double pointer is " << sizeof double_ptr; //8 or 4
cout << "sizeof double double pointer is " << sizeof long_double_ptr; //8 or 4
cout << "sizeof string pointer is " << sizeof string_ptr; //8 or 4
cout << "sizeof vector int pointer is " << sizeof vector_ptr; //8 or 4
double double_num{1020.7};
double_ptr = &int_ptr; //cannot convert ‘int**’ to ‘double*’ in assignment
【问题讨论】:
-
因为类型不仅仅是为了“拟合”一个尺寸。
-
阅读Wikipedia article关于“类型系统”和What is Type safe?可能会有所帮助
-
您是否打算写
double_ptr = &double_num? -
假设你钓到的鱼和你的猫一样大,那么你的猫还是猫不是鱼……
标签: c++ pointers types casting strong-typing