CAST

xiaoxiao2021-03-06  74

I saw articles about CAST today, I haven't noticed it yet. = 1 = // Cast_a.cpp # include Using Namespace STD;

Class interface {Int member;};

Class base {};

Class Derface: Public Interface, Public Base {};

INT main () {base * b = (base *) 100; derived * d1 = reinterpret_cast (b); derived * d2 = static_cast (b);

Cout << "B: << B << endl; cout <<" D1: << D1 << endl; cout << "D2: << D2 << Endl;} ------- -------------------------------------------------- B: 00000064d1: 00000064D2: 00000060 ------------------------------ -------------- Small change, the result is not the same 8) // Cast_b.cpp

#include using namespace std;

Class interface {Int member;};

Class base {};

Class Derface: Public Interface, Public Base {};

INT main () {base * b = (base *) 100; derived * d1 = reinterpret_cast (b); derived * d2 = static_cast (b);

Cout << "B: << B << endl; cout <<" D1: << D1 << endl; cout << "D2: << D2 << Endl;} ------- -------------------------------------------------- B: 00000064d1: 00000064D2: 00000064 -------------------------------------------------------------------------------------------------------- --------------- == why? == Derived objects in memory are as follows: CAST_A.CPP CAST_B.CPP --------------------- <- B | Interface | | BASE | ------------- <- b ------------- | Base | | Interface | ----------- ------ ReinterPret_cast is very simple, just pass the binary value of the pointer to the left. But static_cast will "switch according to relevant type information, if possible, do some offset to the B pointer" (referenced 8). In this example, A, because Base is not the first subclass, STATIC_CAST will do some offset, shift the pointer to the start position of Derived. BBASE is the first subclass, Base originally the same position as the derived, so the result of Static_cast is still pointing to the original position, and the other words are, the offset is 0. -------------------------------------------------- ---------------------------------- PS Don't only focus on the details, and how to think about how to think! How did I write?

转载请注明原文地址:https://www.9cbs.com/read-92970.html

New Post(0)