2010-10-27 14 views
5

के माध्यम से एक्सेस करते समय संकलक किसी सदस्य का स्थान कैसे निर्धारित करता है यह सिर्फ मेरे सिर में कूद गया और मैं इसे समझ नहीं पाया।बेस पॉइंटर

अगर मैं इस तरह एक कोड है:

struct A { char x[100]; }; 

struct B { int data; }; 

struct C : A, B {}; 

#include <iostream> 
using namespace std; 

B* get_me_some_stuff() 
{ 
     static int x = 0; 
     if (++x % 2 == 0) 
       return new B(); 
     else 
       return new C(); 
} 

int main() 
{ 
     B* x = get_me_some_stuff(); 
     B* y = get_me_some_stuff(); 

     x->data = 10; 
     y->data = 20; 

     cout << x->data << " " << y->data << endl; 

     return 0; 
} 

कैसे संकलक data सदस्य की स्मृति स्थान निर्धारित करता है?

उत्तर

2

इस प्रयास करें मेरे लिए आउटपुट:

0x1ae2010 0x1ae2074 

C* से B* को कास्टिंग का कार्य (या अन्य दिशा में) समेत आवश्यक पॉइंटर अंकगणित es।

4

आपके एक्स और वाई पॉइंटर्स वास्तव में बी और सी ऑब्जेक्ट्स (सबसे व्युत्पन्न प्रकार का उपयोग करके) के बी सबोबजेक्ट को इंगित करते हैं।

Example:

int main() { 
    C c; 
    B *pb = &c; // converting the pointer here actually adjusts the address 

    void *pvc = &c; // doesn't adjust, merely type conversion 
    void *pvb = pb; // doesn't adjust, merely type conversion 

    cout << boolalpha; 
    cout << (pvc == pvb) << '\n'; // prints false 
    cout << (&c == pb) << '\n'; // prints true! 
           // (&c is converted to a B* for the comparison) 

    C *pc = static_cast<C*>(pb); // this static_cast, which is UB if pb doesn't 
    // actually point to a C object, also adjusts the address 

    cout << (pc == &c) << '\n'; // prints true 

    return 0; 
} 

इस कहानी का नैतिक? शून्य * (नहीं reinterpret_cast) से static_cast का उपयोग करें, और आप केवल एक ही प्रकार है कि मूल रूप से शून्य करने के लिए कन्वर्ट करने के लिए इस्तेमाल किया गया था करने के लिए शून्य से परिवर्तित कर सकते हैं:

C* x = new C(); 
B* y = x; 
cout << x << " " << y << endl; 

:

reinterpret_cast<C*>(pvb) // undefined behavior 
संबंधित मुद्दे