1.静态成员:C++中引入了static关键字用于定义全局变量和全局函数。
static本质就是全局变量,和类的普通成员变量成员函数没有关系。sizeof(obj)不包括静态成员。
//Object.h //从extern -> static
class Object
{
public:
static int number; //声明static变量(放在类体大括号内)
static void Test(); //声明static函数
};
//Object.cpp
#include "Object.h"
int Object::numer = 1; //static变量定义,加上类范围符限定
void Object::Test()
{
printf("This is test");
}
//main.cpp
#include <stdio.h>
#include "Object.h"
int main()
{
Object::number = 2; //使用
Object::Test();
printf("number:%d\n", Object::number);
return 0;
}
语法特点:
1受public/private限制:如果该函数受private限制,则不允许外部访问该函数,只能够类内其他函数访问
2static函数可以访问类的所有成员,即使成员变量被private限制。
//Object.h
class Object
{
public:
void Call();
private:
static void Test(); //声明static函数
};
//Object.cpp
#include <stdio.h>
#include "Object.h"
void Object::Test()
{
printf("This is test");
}
void Object::Call()
{
Object::Test(); //可以从内部调用,前缀Object::可以省略
}
//main.cpp
#include <stdio.h>
#include "Object.h"
int main()
{ //Object::Test 不能被外调用
Object obj;
obj.Call(); //Call()间接调用Object::Test();
return 0;
}
2.using语句:解除前缀
using namespace std; //前缀std可以省略