1. 程式人生 > >C++之類的靜態成員變量和靜態成員函數

C++之類的靜態成員變量和靜態成員函數

沒有 對象 mes oat tracking eight -m include void

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;
}


技術分享



   

C++之類的靜態成員變量和靜態成員函數