我对 C++ 很陌生。目前我正在查看一个源代码,其中我看到了一些类型转换,但我不明白。
这是代码。
struct str {
char *a;
int b;
};
class F {
public:
char* val;
};
F f1;
任何人都可以解释下面的作业吗?或者这种类型转换有效吗?
str* ptr = (str*) f1->val;
任何人都可以解释下面的作业吗?
它的意思是“假装val
指针指向一个类型的对象str
,即使它被声明指向一个完全不同的类型char
;给我那个指针并相信我知道我在做什么”。
这是假设真正的代码要么声明F * f1;
,要么访问它为f1.val
; 您发布的代码不会编译。
还是那个类型转换有效?
If the pointer really does point to an object of the correct type, then it's valid; otherwise, using the pointer will cause the program to fail in all sorts of catastrophic ways.
Typecasting is something that should very rarely be necessary. If you really do need it, you should never (as in absolutely never, under any circumstances) use that C-style cast; it means "force the conversion with no checks whatsoever, as long as there's some way to do it, even if it makes absolutely no sense". Use static_cast
or dynamic_cast
when you can, and reinterpret_cast
or const_cast
when you're doing something really dodgy. And don't use any of them unless you know what you're doing, and have a very good reason for circumventing the type system.