一个C/C++程序员合不合格的必要条件,我觉得他应该理解了指针、理解了引用,知道通用类型数据在计算机中的内存表示方法,知道什么数据放在栈里,什么数据放在数据区,什么数据放在堆里,知道数据的对齐方式,知道怎么写代码更高效,知道对象的基本模型。下面通过实例逐个介绍这些大家应该掌握的内容:
1.对齐问题
typedef union tagData1 {
double a;
char b;
int c;
} TData1;
typedef union tagData2{
char b;
double a;
int c;
} TData2;
typedef union tagData3 {
char b;
int c;
double a;
} TData3;
printf(“%d %d %d”,sizeof(TData1), sizeof(TData2), sizeof(TData3));
typedef struct tagData1 {
double a;
char b;
int c;
} TData1;
typedef struct tagData2 {
char b;
double a;
int c;
} TData2;
typedef struct tagData3 {
char b;
int c;
double a;
} TData3;
printf(“%d %d %d”,sizeof(TData1), sizeof(TData2), sizeof(TData3));
2.数据在计算机中的表示问题
typedef union tagData1 {
float a;
unsigned char ch[4];
} TData1;
typedef union tagData2 {
int a;
unsignedchar ch[4];
} TData2;
TData1 data1;
data1.a = -3.0;
for (int i = 0; i < 4; i++)
printf(“%02x ”, data1.ch[i]);
TData2 data2;
data2.a = -3;
for (int i = 0; i < 4; i++)
printf(“%02x ”, data2.ch[i]);
3.数据的存放位置
static int a = 0;
void func(int b, int c)
{
static int d = 0;
int e = 0;
char *str = "hello";
TData *pData = new TData;
}
class CData {
public:
void func(int bb, int cc)
{
static int dd = 0;
int ee = 0;
char *str1 = "hello";
TData *pData1 = new TData;
}
private:
static int aa;
int ff;
};
a,b,c,d,e,str,pData,*str,*pData,分别存放在哪里呢?
aa,bb,cc,dd,ee,ff,str1,pData1,*str1,*pData1存放在哪里呢?
4.对象模型问题
class CBase {
public:
void f(){printf(“base f()\n”);}
void g() {printf(“base g()\n”);}
};
class CDerived : public CBase{
public:
void f(){printf(“derived f()\n”);}
void g() {printf(“derived g()\n”);}
};
CBase base;
CDerived derived;
base = derived;
base.f();
base.g();
CBase *pBase = NULL;
CDerived *pDerived = new CDerived();
pBase = pDerived;
pBase->f();
pBase->g();
class CBase {
public:
virtual void f() {printf(“base f()\n”);}
virtual void g() { printf(“base g()\n”);}
};
class CDerived : public CBase{
public:
void f(){printf(“derived f()\n”);}
void g() {printf(“derived g()\n”);}
};
CBase base;
CDerived derived;
base = derived;
base.f();
base.g();
CBase *pBase = NULL;
CDerived *pDerived = new CDerived();
pBase = pDerived;
pBase->f();
pBase->g();
base = *pDerived;
base.f();
base.g();
朋友们,以上的问题你都知道吗,知道为什么是这样吗?