4_1_数据成员绑定.cpp
#include <iostream>
using namespace std;
static string var = "";
using T341 = string;
class A341
{
public:
int func()
{
return var; // 会使用类内部的变量,不是全局的var
}
int var = 0;
using T341 = int;
T341 s; // string s; 数据类型时,会在当前位置按从下到上开始找,所以一般若类内部有定义类型,那么建议定义在类内部第一行
// using T341 = int; // ubuntu类型定义在这里编译会报错,vs下这种写法没问题。可在编译时加上 -fpermissive 将模板代码由出错降为警告,从而让编译通过,不过可能会造成bug
};
int main_3_4_1()
{
return 0;
}
4_3_类成员偏移地址.cpp
#include <iostream>
using namespace std;
#define A343_P(A, m) (int)(&((A*)0)->m) // c语言风格写法打印偏移值,在linux中使用的话同样需要添加 -fpermissive 才能编译通过。。
class A343 final
{
public:
int m_a = 0;
char m_b = 0;
int m_c = 0;
virtual void print()
{
cout << "m_a=" << &A343::m_a << endl; // 不可以,cout 的方式无法正确打印偏移量,输出的全是1
cout << "m_c=" << &A343::m_c << endl;
cout << "m_b=" << &A343::m_b << endl;
printf("m_a的偏移量=%d\n", &A343::m_a); // 可以, 0, 注意加上 A343:: ,就是类的成员变量指针的值
printf("m_b的偏移量=%d\n", &A343::m_b); // 4
printf("m_c的偏移量=%d\n", &A343::m_c); // 8
// cout << "m_a的偏移量=" << A343_P(A343, m_a) << endl; // 可以,但是需要 -fpermissive
// cout << "m_b的偏移量=" << A343_P(A343, m_b) << endl;
// cout << "m_c的偏移量=" << A343_P(A343, m_c) << endl;
}
};
int main_3_4_3()
{
// 打印类成员相对类对象首地址的偏移
A343().print();
cout << sizeof(A343) << endl; // 24 ,final不会改变virtual让编译器生成虚函数表的行为
return 0;
}
4_8_虚基类表.cpp
#include <iostream>
using namespace std;
class A348
{
public:
int grand = 0;
A348() { cout << "A348 this=" << hex << this << endl; }
};
class B348 : virtual public A348 // 一个虚继承,编译器就会在类中加一个虚基类表指针 vbptr
{
public:
int b = 0;
B348() { cout << "B348 this=" << hex << this << endl; }
};
class C348 : public virtual A348
{
public:
int c = 0;
C348() { cout << "C348 this=" << hex << this << endl; }
};
class D348 : public B348, public C348
{
public:
int d = 0;
D348() { cout << "D348 this=" << hex << this << endl; }
void printVarAddr()
{
printf("%d, ", &D348::grand);
printf("%d, ", &D348::b);
printf("%d, ", &D348::c);
printf("%d\n", &D348::d);
}
};
int main_3_4_8()
{
// 虚基类表指针 vbptr 指向虚基类表,虚基类表中记录虚基类成员在子孙类中的偏移量,只有当孙类对象使用虚基类成员时才会用到虚基类表。
cout << sizeof(A348) << "," << sizeof(B348) << "," << sizeof(C348) << "," << sizeof(D348) << "," << endl;
// 虚继承时,爷爷类的成员变量时放在孙类对象内存结构的最下面。。子类变量还是按继承顺序放
D348().printVarAddr();
return 0;
}
虚继承时内存结构