前言
C++对象模型可以概括为以下2部分:
- 语言中直接支持面向对象程序设计的部分,主要涉及如构造函数、析构函数、虚函数、继承(单继承、多继承、虚继承)、多态等等。
- 对于各种支持的底层实现机制。
在c语言中,“数据”和“处理数据的操作(函数)”是分开来声明的,也就是说,语言本身并没有支持“数据和函数”之间的关联性。在c++中,通过抽象数据类型(abstract data type,ADT),在类中定义数据和函数,来实现数据和函数直接的绑定。
概括来说,在C++类中有两种成员数据:static、nonstatic;三种成员函数:static、nonstatic、virtual。
1.基础知识
#include "iostream"
using namespace std;
class C1
{
public:
int i; //4
int j; //4
int k; //4
protected:
private:
}; //12
class C2
{
public:
int i;
int j;
int k;
static int m; //4
public:
int getK() const { return k; } //4
void setK(int val) { k = val; } //4
protected:
private:
}; //24 16 12(铁钉的不对) 答案就是12
struct S1
{
int i;
int j;
int k;
}; //
struct S2
{
int i;
int j;
int k;
static int m;
}; //
int main()
{
printf("c1:%d \n", sizeof(C1));//12
printf("c2:%d \n", sizeof(C2));//12
printf("s1:%d \n", sizeof(S1));//12
printf("s2:%d \n", sizeof(S2));//12
system("pause");
}
2. 编译器对属性和方法的处理机制
-
C++类对象中的成员变量和成员函数是分开存储的
成员变量:
普通成员变量:存储于对象中,与struct变量有相同的内存布局和字节对齐方式
静态成员变量:存储于全局数据区中
成员函数:存储于代码段中。 -
C++编译器对普通成员函数的内部处理
#include "iostream"
using namespace std;
class Test
{
public:
Test(int a,int b) //---->Test(Test *this,int a,int b)
{
this->a=a;
this->b=b;
}
void printT()
{
cout<<"a: "<<a<<endl;
cout<<"b: "<<b<<endl;
}
//1 与const的位置无关
//const void OpVar(int a,int b)
//void const OpVar(int a,int b)
//2 const 修饰的是谁
//2-1 const修饰的形参a,不是
//2-2 const修饰的是属性this->a this->b
//2-3 const修饰的是this指针所指向的内存空间
void OpVar(int a,int b) //const //--->void OpVar(const Test *const pThis,int a,int b)
{
a=100;
this->a=100;
this->b=200;
cout<<"a: "<<a<<endl;
cout<<"b: "<<this->b<<endl;
}
protected:
private:
int a;
int b;
};
void main()
{
Test t1(1,2);
t1.printT();//-----> printT(&t1)
cout<<"hello..."<<endl;
system("pause");
return ;
}
主要关注其中的const
3. 总结
- C++类对象中的成员变量和成员函数是分开存储的。C语言中的内存四区模型仍然有效!
- C++中类的普通成员函数都隐式包含一个指向当前对象的this指针。
- 静态成员函数、成员变量属于类
静态成员函数与普通成员函数的区别
静态成员函数不包含指向具体对象的指针
普通成员函数包含一个指向具体对象的指针
4、 This 指针
5. 全局函数PK成员函数
- 把全局函数转化成成员函数,通过this指针隐藏左操作数
Test add(Test &t1, Test &t2)===》Test add(Test &t2) - 把成员函数转换成全局函数,多了一个参数
void printAB()===》void printAB(Test *pthis) - 函数返回元素和返回引用
Test& add(Test &t2) //*this //函数返回引用
{
this->a = this->a + t2.getA();
this->b = this->b + t2.getB();
return *this; //*操作让this指针回到元素状态
}
Test add2(Test &t2) //*this //函数返回元素
{
//t3是局部变量
Test t3(this->a+t2.getA(), this->b + t2.getB()) ;
return t3;
}