1 数据成员绑定时机
1.1 类中类型及变量绑定时机
EG:
#include <iostream>
using namespace std;
string c; //全局变量c
typedef string mytype;
class A
{
public:
mytype d; //mytype被解释为string类型
int test(mytype a) //成员参数中的mytype被解释成全局的mytype(string类型)
{
mytype b; //函数中的mytype被解释为int类型
return c;
}
public:
int c; //成员变量c
typedef int mytype;
mytype e; //mytype被解释为int类型
};
int main()
{
return 0;
}
建议:建议如果类中有typedef类型重命名放在类的开头,避免和外部类型重命名混淆
2 类成员变量的对齐及偏移
2.1 类成员变量的对齐及偏移
默认情况下一些编译器会以最大成员占用的字节数进行字节对齐,这样做虽然需要消耗更多的内存空间,但是可以提高运行效率
EG:
#include <iostream>
using namespace std;
string c; //全局变量c
typedef string mytype;
#pragma pack(1) //开始一字节对齐
class A
{
public:
int a;
double b;
char c;
};
#pragma pack() //恢复默认对齐方式
class B
{
public:
int a;
double b;
char c;
virtual void func(){}
};
int main()
{
//使用字节对齐
cout << "使用一字节对齐" << endl;
cout << "A类在一字节对齐下的大小:" << sizeof(A) << endl;
printf("A中a成员变量的偏移值%d\n", &A::a); //使用这种方式打印的是类成员变量的偏移量
printf("A中b成员变量的偏移值%d\n", &A::b);
printf("A中c成员变量的偏移值%d\n\n\n", &A::c);
//使用默认字节对齐,不同的编译器可能不一样,这里是VS2017,类中默认以占用字节数最大的成员变量对齐
cout << "