[英]‘void*’ is not a pointer-to-object type
struct limit{
int up;
int down;
};
void *x;
struct limit *l;
l->up=1;
l->down=20;
x=l;
cout<<x->up;
這是我的代碼的一部分,我在最后一行'void *'中出錯, 這不是指向對象的指針類型 。 我知道代碼的最后一行是錯誤的。 我只想知道如何使用x
變量上下打印值。
在這一部分:
struct limit *l;
l->up=1;
l->down=20;
您正在取消引用未初始化的指針l
,這將導致未定義的行為 。 但是,即使您正確地初始化了它,將其分配給void*
,也無法取消引用void
指針:
void* x = l;
cout<< x->up;
您需要將其顯式轉換回struct limit*
:
void* x = l;
struct limit * y = static_cast<struct limit*>(x);
cout << y->up;
甚至更好:避免一開始使用void*
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.