C++之类的静态成员变量和静态成员函数

static静态成员函数

在类中。static 除了声明静态成员变量,还能够声明静态成员函数。

普通成员函数能够訪问全部成员变量。而静态成员函数仅仅能訪问静态成员变量。



我们知道。当调用一个对象的成员函数(非静态成员函数)时,系统会把当前对象的起始地址赋给 this 指针。而静态成员函数并不属于某一对象。它与不论什么对象都无关,因此静态成员函数没有 this 指针。既然它没有指向某一对象,就无法对该对象中的非静态成员进行訪问。

能够说。静态成员函数与非静态成员函数的根本差别是:非静态成员函数有 this 指针。而静态成员函数没有 this 指针。由此决定了静态成员函数不能訪问本类中的非静态成员。

静态成员函数能够直接引用本类中的静态数据成员,由于静态成员相同是属于类的,能够直接引用。在C++程序中,静态成员函数主要用来訪问静态数据成员。而不訪问非静态成员。

假设要在类外调用 public 属性的静态成员函数。要用类名和域解析符“::”。

如:


下面是一个完整演示样例。
<pre name="code" class="cpp">
#include<iostream>
#include<string>
using namespace std;

class Student{
private:
	string name;
	int age;
	float score;
	static int number; //定义静态成员变量
	static float total;
public:
	Student(string name,int age,float score);
	Student(const Student & s);
	~Student();
	void setName(string n);
	string getName();
	void setAge(int a);
	int getAge();
	void setScore(float s);
	float getScore();
	void say();
	static float getAverage();
};
/*注意。假设构造函数的形參和 类的成员变量名字一样。必须採用 this -> name = name ,而不能够 写成 name = name*/
Student::Student(string name,int age,float score){
	this->name = name;
	this ->age = age;
	this ->score = score;
	number++;
	total += score;
}

Student::Student(const Student & s){
	this ->name = s.name;
	this ->age = s.age;
	this ->score = s.score;
}

Student::~Student(){}
string Student::getName(){
	return this->name;
}
int Student::getAge(){
	return this->age;
}
float Student::getScore(){
	return this ->score;
}

void Student::setName(string n){
	this ->name = n;
}

void Student::setAge(int a){
	this ->age =a ;
}

void Student::setScore(float s){
	this->score =s;
}

void Student::say(){
	cout << this->name <<" : " << this->age <<" : " << this ->score << " : " << Student::number <<endl;
}

float Student::getAverage(){
	if(number == 0)
	{
		return 0;
	}
	else
		return total/number;
}
//静态变量必须初始化。才干够使用
int Student::number = 0;
float Student::total = 0;

int main(int argc,char*argv[])
{
	//即使没有创建对象也能够訪问静态成员方法
	cout << "没有学生的时候的平均成绩"<< Student::getAverage() <<endl;
	
	Student s1("lixiaolong",32,100.0);
	Student s2("chenglong",32,95.0);
	Student s3("shixiaolong",32,87.0);
	s1.say();
	s2.say();
	s3.say();
	cout << "平均成绩为" << Student::getAverage() <<endl;
	system("pause");
	return 0;
}





原文地址:https://www.cnblogs.com/liguangsunls/p/7281411.html