day03C++-静态成员变量和静态成员函数、C++面向对象模型初探
静态成员变量和静态成员函数
static关键字的由来
有没有一个属性是属于所有的对象的。
代码如下:
class Test
{
public:
int getC()
{
return a;
}
private:
int c;
static int a;
};
//给类中的静态成员赋值
int Test::a = 10;
int main()
{
Test t1;
cout << t1.getC() << endl;;
system("pause");
return 1;
}
类中静态函数的调用方法如下:
cout << t1.getC() <<Test::getC() <<endl;;
问题:在静态成员函数中,能调用普通成员属性或者方法吗?
这个问题,应该站在类和对象关系中考虑问题,
在静态函数中不能访问普通属性,原因如下:
因为,在静态函数中,编译器分不清楚是哪个对象的a,所以编译器会报错。
而静态成员属性可以,因为静态成员属于整个类的。
这个时候应该考虑,第一次课的问题:C++编译器如何区分是哪个类的对象调用的类的属性和方法的?
C++面向对象模型初探:(针对的上面的那个问题)
思考问题:C++怎么支持继承、多态、析构函数
实验代码如下:
class Test1
{
public:
int a;
int b;
int c;
int getA()
{
return a;
}
};
class Test2
{
public:
int a;
int b;
int c;
int static d;
static int getB()
{
return 1;
}
};
struct s1
{
int a, b, c;
static int m;
};
struct s2
{
int a, b, c;
};
int main()
{
cout << "the size of test is " << sizeof(Test1) << endl;
cout << "the size of test2 is " << sizeof(Test2)<<endl;
cout << "the size of s1 is " << sizeof(s1) << endl;
cout << "the size of s2 is " << sizeof(s2) << endl;
system("pause");
return 1;
}
输出结果:
the size of test is 12
the size of test2 is 12
the size of s1 is 12
the size of s2 is 12
请按任意键继续. . .
内存大小都是12;
编译器对属性和方法的处理机制
通过上面的案例,我们可以的得出:
1)C++类对象中的成员变量和成员函数是分开存储的
成员变量:
普通成员变量:存储于对象中,与struct变量有相同的内存布局和字节对齐方式
静态成员变量:存储于全局数据区中
成员函数:存储于代码段中。
2)C++编译器对普通成员函数的内部处理
**
1、C++类对象中的成员变量和成员函数是分开存储的。C语言中的内存四区模型仍然有效!
2、C++中类的普通成员函数都隐式包含一个指向当前对象的this指针。
3、静态成员函数、成员变量属于类
静态成员函数与普通成员函数的区别:
静态成员函数不包含指向具体对象的指针
普通成员函数包含一个指向具体对象的指针
**