简体   繁体   English

TypeCasting结构和类

[英]TypeCasting Struct and Classes

I am very new to C++. 我是C ++的新手。 Currently I am reviewing a source code where I saw some typecasting, but I didn't understand it. 目前,我正在查看源代码,其中看到了一些类型转换,但我不理解。
Here is the code. 这是代码。

struct str {
    char *a;
    int b;
};

class F {
public:
    char* val;
};  

F f1;  

Can anyone explain the below Assignement Please.or is that typecasting valid?? 谁能解释下面的Assignment。或者类型转换有效吗?

 str* ptr = (str*) f1->val;  

Can anyone explain the below Assignement Please. 任何人都可以解释以下分配。

It means "pretend that the val pointer points to an object of type str , even though it's declared to point to a completely different type char ; give me that pointer and trust that I know what I'm doing". 它的意思是“假装val指针指向类型为str的对象,即使已声明它指向完全不同的char类型;请给我该指针,并相信我知道自己在做什么”。

That's assuming that the real code either declares F * f1; 假设实际代码声明为F * f1; , or accesses it as f1.val ; ,或以f1.val访问它; the code you've posted won't compile. 您发布的代码无法编译。

or is that typecasting valid?? 还是那个类型转换有效?

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; 如果确实需要它,则绝对不能(在任何情况下绝对不要)使用C样式转换; 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. 可以的话,请使用static_castdynamic_cast ;在做一些实际的动作时,请使用reinterpret_castconst_cast 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. 除非您知道自己在做什么,并且有很好的理由规避类型系统,否则不要使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM