C++静态成员函数和静态成员变量的探索

静态数据成员属于类,非属于类对象,所以,定义位置就有了限制。

静态数据成员要实际地分配空间,故不能在类的声明中定义(只能声明数据成员)。类声明只声明一个类的“尺寸和规格”,并不进行实际的内存分配,所以在类声明中写成定义是错误的。它也不能在头文件中类声明的外部定义,因为那会造成在多个使用该类的源文件中,对其重复定义。

静态成员函数只能调用静态成员,要调用非静态成员,只能通过类对象,但一般成员函数可以调用静态成员函数。

下面是一个综合性示例,对上面所说都有涉及:

#include <iostream>
#include <string>

using namespace std;

class Student
{
private :
	int _num;
	int _score;
    

public :

	static string _classRoom;  //静态数据成员

	//构造函数
	Student(int num,int score):_num(num),_score(score){}

	//在类内定义和声明函数  输出编号
	void getNum(){
	cout<<"the num is :"<<this->_num<<endl;
	}
	//在类内声明和在类外定义  输出成绩
	void getScore();

	//在类内声明静态函数  输出班级  如果要输出非静态成员需要传递对象 如同这个函数
    static	void getRoom1(Student s);
	//在类内定义静态函数  输出班级  输出静态数据成员 如同此函数
	static void  getRoom2(){
	cout<<"the room is :"<<_classRoom<<endl;
	}
};
//只能在类外对静态数据成员赋值  私有成员也不例外
string Student::_classRoom="计科112班";

//在类外定义的函数 用来输出成绩
void Student::getScore(){
   cout<<"the score is :"<<this->_score<<endl;
}
//输出学生班级
void Student::getRoom1(Student s){
  cout<<"the num   is :"<<s._num<<endl
	  <<"the score is :"<<s._score<<endl
	  <<"the score is :"<<_classRoom<<endl;
}
int main(){
	Student stu(111,98);
	stu.getNum();
	stu.getScore();
	stu.getRoom2();
	Student::_classRoom="计算机专业";
	Student::getRoom1(stu);
    return 0;
}


运行结果:




原文地址:https://www.cnblogs.com/riasky/p/3430720.html