再一次吐槽一下,c++这门语言实在是太复杂了,语法规则这么多,关于static,还是有很多需要注意的地方,总结一下吧:
首先,我们知道在c中,static的作用可以用来改变变量的生存期和作用域,函数的作用域,那么在面向对象导向的c++中,又有什么作用呢?
我们考虑这样一个问题,一个学生类Student,这个类中有一个public变量s_num表示整个班级的学生的数量,那么这个变量应该设置成什么样?那么当通过对象访问的时候,应该是全体学生的数量,可是每一个对象维护的是自己对象的属性啊,这样就不能表示全体对对象啊,这个时候,我们把这个变量交给类来管理,上升到类的层面,它是“类的属性”,也就是说这个变量可以不依赖对象的存在而存在,这个变量就是我们的static变量的了,我们可以看出static变量还是具有它不可替代的地位吧。
进入主题,如何在类中使用static变量以及这个变量的作用有哪些呢?
首先是它的初始化,有人会想,既然是类的一部分,我可不可以在类的声明中初始化呢?答案是最好不要,如果你在类的构造函数中声明一个static成员变量,那么每一次构造对象的时候都会初始化这个值,也不要放在头文件中,那最好放在哪里呢?可以放在全局区,例如main前面
例如:我们可以这样访问,Student::s_num,也可以Student student; student.s_num;那如果我们的s_num是private呢?这样第二种方式就不能用了,由此我们需要构造我们的static成员函数来访问static成员变量
static成员函数没有this指针,我们也可以通过类来直接调用
看一个例子:
#ifndef EMPLOYEE_H
#define EMPOLYEE_H
class Employee
{
public:
Employee(const char *const , const char *const);
~Employee();
const char *getFirstName() const;
const char *getLastName() const;
static int getCount();
private:
char *firstName;
char *lastName;
static int count;//声明为了private
};
#endif
类的实现文件
#include <iostream>
#include <cstring>
#include "employee.h"
using namespace std;
int Employee::count = 0;//在这里初始化,但是前面不能再加static了
Employee::Employee(const char *const first, const char *const last)
{
firstName = new char[strlen(first) + 1];
lastName = new char[strlen(last) + 1];
strcpy(firstName, first);
strcpy(lastName, last);
count++;
cout<<"constructor called for"<<firstName<<" " <<lastName<<endl;
}
int Employee::getCount()//也不能再加static了
{
return count;
}
Employee::~Employee()
{
cout<<"destructor called for"<<firstName<<" "<<lastName<<endl;
delete[] firstName;
delete[] lastName;
count--;
}
const char* Employee::getFirstName() const
{
return firstName;
}
const char* Employee::getLastName() const
{
return lastName;
}
测试函数:
#include <iostream>
#include "employee.h"
using namespace std;
int main()
{
Employee person1("john","maclian");
Employee person2("eyan","sumhaird");
cout<<"the cout is "<<person1.getCount()<<endl;
cout<<"the cout is "<<Employee::getCount()<<endl;//通过类来访问
return 0;
}
总结几点:
1.初始化问题,在哪里初始化
2.如果是public则通过类本身和对象可以直接访问变量
3.static成员变量初始化和static成员函数实现的时候都不能再加static了
4.静态成员函数不能访问非静态成员变量和非静态成员函数
5.非静态成员函数却可以访问静态成员变量和静态成员函数