64,646
社区成员
发帖
与我相关
我的任务
分享
int a[2]={1,2};
int b[2]={3,4};
//a=b;
//这句编不过,但很明显,楼上的意图本来是想将a作为指针指向数组b;或者想将数组b的数据赋予数组a;
//a----------0x0012ff24
// [0]------1
// [1]------2
//b----------0x0012ff1c
// [0]------3
// [1]------4
*(void **)a=*(void **)b;
//a----------0x0012ff24 //a,b的地址都没变;
// [0]------3 //也不是说整个数组a的数据都等于数组b; a[0]==b[0]; a[1]!=b[1];
// [1]------2
//b----------0x0012ff1c
// [0]------3
// [1]------4
#include<iostream>
using namespace std;
struct testBase
{
virtual void show() {cout << "base" << endl;}
};
struct testDrv: public testBase
{
virtual void show() {cout << "Derived" << endl;}
void InitClassDefault(testBase* In)
{
*(void**)this = *(void**)In;
}
};
int main(int argc, char** argv)
{
testBase tb;
testBase *pb=new testDrv();
pb->show();
dynamic_cast<testDrv *>(pb)->InitClassDefault(&tb);
pb->show();
return 0;
}
road tibet;
tibet._long = 1956; //青藏铁路长1956
*(int*) (&tibet) = *(int*) (&bmw); //路长200
#include <stdio.h>
struct road {
int _long; //类或结构的第一个元素
//...
};
struct car {
int oil;
//...
};
struct driver {
char* name;
//...
};
void run(int oil) {
printf("-----------%d\n", oil);
}
void delay(char* name) {
printf("-----------%s\n", name);
}
void main() {
car bmw;
bmw.oil = 200;
run(bmw.oil);
char* p = &bmw;
int* poil = (int*)p; //在内存里,假如bmw汽车所在的地址为0x888EEE,那么它的第一个元素oil所在的地址,就是对象本身的地址,即0x888EEE.
//所以,以下调用
run(*poil);
//等价于
run(*(int*)p);
//也就是说*(int*)p的意义为,获得汽车指针p处的第一个元素(类型为int)的值
//***************总结******************
//当一个指针,我们知道它的类型时,可以直接取它的第一个元素的值
//pcar.oil
//proad._long
//当我们不知道这个指针的类型,但又知道它的第一个元素的类型时,就只能这样取这个元素的值了
//*(int*)p
//以此类推
driver rene;
rene.name = "rene's baby";
delay(rene.name);
driver* p2 = &rene;
char** pname = (char**)p2;
delay(*pname);
//等价于
delay(*(char**)p2);
}