C++静态类成员

2022-10-31 13:21:20 浏览数 (1)

静态类成员就是不管这个类是否有已实例化的对象存在,这个成员都一直存在。

也就是说,静态类成员是绑定在类上的,而不是绑定在对象上的。

声明静态类成员的方式就是在函数前加入static关键字。

静态类成员通常适用于当一个类的所有对象之间需要共享同一份数据的时候,这样子能节省空间,提高效率。

在C 11之前,只有int或者enum类型能在声明的时候被初始化。(但是C 11及以后则不存在这个问题)

如何访问静态数据成员?

对于public的静态数据成员,我们只需要用类似于

代码语言:javascript复制
Test::data

这样子的格式来访问即可。

对于private或者protected的静态数据成员,我们需要为他们创建一个静态成员函数来返回他们的值。同样的,静态成员函数是绑定在类上而不是在对象上的。

代码:

Employee.h

代码语言:javascript复制
#pragma once
#include<string>
class Employee
{
public:
	Employee(const std::string&, const std::string&);

	~Employee();

	std::string getFirstName() const;
	std::string getLastName() const;

	//static member function
	static unsigned int getCount();

private:
	std::string FirstName, LastName;

	static unsigned int count;
};

Employee.cpp

代码语言:javascript复制
#include "Employee.h"
#include<iostream>
using namespace std;

//define and initialize static data member at global namespace scope
unsigned int Employee::count = 0;//cannot include keyword static

//define static member function that returns number of
//Employee objects instantiated (declared static in Employee.h)
unsigned int Employee::getCount()
{
	return count;
}

//constructor initializes non-static data members and
//increment static data member count
Employee::Employee(const string& first, const string& last)
	:FirstName(first),LastName(last)
{
	  count;
	cout << "Employee constructor for " << FirstName << ' ' << LastName << " called." << endl;
}

Employee::~Employee()
{
	cout << "~Employee() called for " << FirstName << ' ' << LastName << endl;
	--count;//decrement static count of employees
}


//return first name of employee
string Employee::getFirstName()const
{
	return FirstName;
}

string Employee::getLastName()const
{
	return LastName;
}

main.cpp

代码语言:javascript复制
#include<iostream>
#include"Employee.h"
using namespace std;

int main()
{
	cout << "Number of employees before instantiation of any objects is " << Employee::getCount() << endl;

	//the following scope created and destroys Employee objects before main terminates
	{
		Employee e1("Susan", "Baker");
		Employee e2("Robert", "Jones");

		cout << "Number of employees after objects are instantiated is "
			<< Employee::getCount() << endl;

		cout << "nnEmployee 1: "
			<< e1.getFirstName() << " " << e1.getLastName()
			<< "nEmployee 2: "
			<< e2.getFirstName() << ' ' << e2.getLastName()
			<< "nn";
	}//end nested scope in main

	//no objects exist, so call static member function getCount again
	//using the class name and the scope resolution operator
	cout << "nNumber of employees after objects are deleted is "
		<< Employee::getCount() << endl;
}

特别的,对于main.cpp中,用一对大括号括起来的代码块,他们的变量作用域只是这个块之中,当这一块结束之后,里面的数据成员也就被清理了。

转载请注明来源:https://www.longjin666.top/?p=833

0 人点赞