siatic用法与const用法
静态成员和常量成员
- 静态数据成员的初始化
- 类外
- 类型
类名::静态成员名=初始值 - 访问静态数据成员:
类名::静态成员名对象名.静态成员名
- 常量成员:
常量数据成员和常量成员函数- 常量数据成员 必须通过
成员初始化列表。 - 常量成员函数:
只读函数 - 常量成员函数中
this指针是只读类型的const 类名 *this
- 常量数据成员 必须通过
静态数据成员被所有对象所共享
静态成员函数和非静态成员函数可以访问静态数据成员静态成员函数不能访问非静态数据成员
statie用法
静态全局变量(文件作用域)和静态局部变量(静态全局区)静态函数(文件作用域)静态数据成员静态成员函数
const用法
- const修饰变量
- const与指针
常量数据成员常量成员函数
练习代码
A.h头文件
class CA
{
public:
CA(int a);
~CA();
//静态成员函数中没有this指针
static int GetA()
{
return m_a;
//return m_b;编译报错
}
int GetA1()
{
//return this->m_a;
return this->m_b;
}
//常量成员函数中:this指针是只读类型
int GetC() const
{
m_a = 200;
int x = 10;
x += 200;
//常量成员函数中this指针是只读类型的 const 类名 *this
//this->m_b=10;//编译报错
return m_c;
}
private:
//静态数据成员
static int m_a;
int m_b;
const int m_c;
};
A.cpp文件
#include "A.h"
int CA::m_a = 100;
CA::CA(int a) :m_c(a)//成员初始化列表
{
}
CA::~CA()
{
}
main.cpp文件
int main()
{
CA ca(10);
//静态成员是属于类的。
cout << CA::GetA() << endl;
//静态私有数据成员不能在类外访问
//cout << ca.m_a << endl;
//类内存所占字节数:非静态数据成员内存大小之和
cout << sizeof(CA) << endl;
return 0;
}