-
#include <iostream>
-
using namespace std;
-
class A
-
{
-
public:
-
A()
-
{
-
a=1;
-
b=2;
-
}
-
void fun()
-
{
-
cout<<"a:"<<a<<" "<<"b:"<<b<<endl;
-
// b=2;
-
}
-
private:
-
int a;
-
int b;
-
};
-
class B
-
{
-
public:
-
B()
-
{
-
c=6;
-
c=3;
-
}
-
void fun()
-
{
-
cout<<"c:"<<c<<endl;
-
//b=2;
-
}
-
private:
-
int d;
-
int c;
-
//int b;
-
};
-
void main()
-
{
-
A a;
-
B *b=(B *)(&a);
-
b->fun();
-
-
}
由于B类中存放两个变量和A类相同,指针b强制类型转换指向a的首地址,通过指针调用fun函数读取c的变量,对应A类中的b变量的存储空间,所以输出为2。如下所示:
阅读(386) | 评论(0) | 转发(1) |