并排定义指针和类型问题

Definig pointer side-by-side and type issues

所以代码:

int *mine, *yours; // note this declaration 
mine = new int;
yours = mine;
*yours = 8;
delete yours;
*mine = 12;
mine = NULL;

我们可以像这样定义我的指针吗?这段代码有什么问题吗?

此外,

size_t length = 47;
int* plength = &length;

这段代码可以吗?

Can we define pointers mine, yours like this? And is there anything wrong with this code?

非常好。当你以这种方式有相同类型的指针声明时,我建议你可以使用 typedef 来更清楚,

typedef int *p_int;
p_int yours, mine; // Both members are pointers to integer type

size_t & int 是不同的类型,整数指针 plength 只能指向整数成员的地址,不能指向其他成员的地址。

Can we define pointers mine, yours like this?

是的。如果你做不到,编译器会抱怨的。

And is there anything wrong with this code?

是的。两个指针都指向同一个对象,您通过 yours 删除它后通过 mine 访问它。访问已删除对象的残余会出现未定义的行为。

Is this code fine?

不,大概是编译器告诉你的。 size_tint 是不同的类型,因此不能为 int* 指针指定 size_t 对象的地址(没有恶意转换)。