静态成员对象
1.该静态成员对象是属于类的,而非某个对象。
2.该静态成员对象为类的所有对象所共享一份
3.该静态成员不占用类对象的空间。
静态成员函数
class 类名
{
public:
static 返回值 函数名(形参列表)
{
//静态成员函数的函数体
//静态成员函数体中只能访问类中的静态数据,不可以访问类中非静态数据。
//因为static修饰的成员函数没有的this指针。所以不可调用类中的非静态数据。
}
};
static修饰的成员函数并非修饰函数的存储形式,修饰的是成员函数的级别,这个级别就是此将成员函数提升为一个真正带有全局作用域的函数。
只不过此函数是隐藏在类的作用域之中而已。
所以此时该成员函数也就没有this指针。
所以此函数不能调用类中的非静态属性或方法。
此函数是为了整个类而服务的,而非某个对象,不依赖于对象的调用,可以直接使用类域 : : 调用。
例:
创建类:
#include <iostream>
using namespace std;
class Stu
{
private:
string name;
int age;
static int count;
public:
Stu(string name, int age)
{
this->name = name;
this->age = age;
count++;
cout << "Stu的构造" << endl;
}
//2.返回本对象。
const Stu setName(string name)
{
this->name = name;
return *this;
}
string getName()const
{
return this->name;
}
int getAge()const
{
return this->age;
}
static int get_Count()
{
return count;
}
void showName()const
{
cout << this->name << endl;
}
~Stu()
{
cout << "Stu的析构" << endl;
}
Stu(const Stu& other)
{
this->name = other.name;
this->age = other.age;
cout << "Stu的拷贝构造" << endl;
}
};
类外对静态变量初始化:
//静态全局变量类外初始化
int Stu::count = 0;
全局函数:
void showInfo(const Stu& stu)
{
cout << "姓名:" << stu.getName() << ",年龄:" << stu.getAge() << endl;
}
主函数:
int main()
{
Stu stu("zhangsan",18);
showInfo(stu);
stu.setName("lisi").showName();
cout << "-------------" << endl;
Stu* stu2 = new Stu("zhangsan",20);
stu2->setName("lisi");
stu2->showName();
delete stu2;
cout << "------------------" << endl;
cout << Stu::get_Count() << endl; //2, 一共创建了两个对象
return 0;
}
运行结果: