C++用指针访问private 成员

来源:互联网 发布:易道打车软件 编辑:程序博客网 时间:2024/05/29 12:30

//

//  main.cpp

//  使用指针访问类中的私有变量

//

//  Created by 就不告诉你我是谁 on 15-7-25.

//  Copyright (c) 2015 xuqigang. All rights reserved.

//

#include <iostream>

using namespace std;

class Class1{

public:

    Class1(){

        

    }

    

private:

    int a=10;

    int k=100;

    

};




int main(int argc, const char * argv[])

{


    // insert code here...

    std::cout <<"Hello, World!\n";

    Class1 *p;

    Class1 D;

    p=&D;//对象D的地址也就是对象D中首个成员变量的地址;  而此刻p中存的地址也是首个成员变量的地址

    

    int *f=(int *)p;//指针转型

    printf("%d\n",*f);//解引用便得到私有成员的值

    return 0;

}


0 0