现在的位置: 首页 > 综合 > 正文

C++对象 内存细节(一)

2019年08月22日 ⁄ 综合 ⁄ 共 1289字 ⁄ 字号 评论关闭
        首先考虑成员变量在类的继承中的行为 代码41-55行,基类指针可以准确的判断出哪些变量是基类可见的,哪些是“理论上”不可见的。这样的行为是C++类的内存结构所实现的。通过sizeof()我们可以发现这三个类的对象的大小分别为8、12、16。所以这三个类在内存中的摆放应该是这的:
                      
        而箭头所指的内存地址就是对象所在的位置。根据你给定的指针的类型的不同,你就只能看到受到限制的这一部分内容了。这里的 三种指针的访问范围就对应了那三个框的范围。
        由此可以简单的“越狱”访问你理论上不能访问的东西,这里就不再解释了。
        关于函数的部分下次再说吧 = =
#include <iostream>
#include <cstdio>
using namespace std;

//为了方便测试,所有的成员变量都先设定为public

class Parent
{
public:
    int zero;
public:
    Parent() { this->zero = 0; }
    virtual void fun() { cout << "Parent::fun" << endl; }
};

class ChildOne : public Parent
{
public:
    int one;
public:
    ChildOne() { Parent::Parent(); this->one = 1; }
    virtual void fun(){ cout << "ChildOne::fun" << endl; }
};

class ChildTwo : public ChildOne
{
public:
    int two;
public:
    ChildTwo() { Parent::Parent(); this->two = 2; }
    virtual void fun(){ cout << "ChildTwo::fun" << endl; }
};

int main()
{
    Parent *p;
    ChildOne *o;
    ChildTwo *t;

//成员变量
    p = new Parent();
    cout << p->zero << endl;
    o = new ChildOne();
    cout << o->zero << endl;
    cout << o->one << endl;

    delete p;
    p = new ChildOne();
    cout << p->zero << endl;
//  cout << p->one << endl; 无法访问
    delete p;
    p = (Parent*)new ChildTwo();
    cout << p->zero << endl;
//  cout << p->one << endl; 无法访问
//  cout << p->two << endl; 无法访问

//  cout << sizeof(*p) << endl;
//  cout << sizeof(*o) << endl;
//  cout << sizeof(*t) << endl;




//成员函数
    p = new Parent();
    p->fun();

    delete p;
    p = (Parent*)new ChildOne();
    p->fun();

    delete p;
    p = (Parent*)new ChildTwo();
    p->fun();

    return 0;
}

抱歉!评论已关闭.