静态数据成员与静态成员函数
1. 静态数据成员
#include<iostream>
#include<cstring>
using namespace std;
class student{
public:
student(char *pname="no name")
{
cout<<"create one student\n";
strcpy(name,pname);
noofstudents++;//静态成员:每创建一个对象,学生人数+1
cout<<noofstudents<<endl;
}
~student()
{
cout<<"destruct one student\n";
noofstudents--;//静态成员:每创建一个对象,学生人数+1
cout<<noofstudents<<endl;
}
static int number(){return noofstudents;
}
protected:
static int noofstudents;
char name[40];
};
int student::noofstudents=0;//静态数据成员在类声明外分配空间和初始化
//::可以用来表示名字百空间,也可以用在类外面度定义类函数。
//.表示类实例调知用类中的公有函数。
void fn()
{
student s1;
student s2;
cout<<student::number()<<endl;//调用静态成员函数用类名引导
}
int main()
{
fn();
cout<<student::number()<<endl;//调用静态成员函数用类名引导
return 0;
}
//333
公共静态成员可以被类的外部访问,保护或私有的静态成员只能被类的内部访问。
在类的外部,访问静态数据成员的形式可以用s1.noofstudents,并且等价于s2.noofstudents,更通常的用法是students::noofstudents(不能用student.noofstudents)。其意义是:静态数据成员是属于student类的,而不是属于某个特定对象的,也不需要依赖某个特定对象的数据。
2.静态成员函数
#include<iostream>
#include<cstring>
using namespace std;
class student{
public:
static int number()
{
return noofstudents;
}
protected:
static int noofstudents;
char name[40];
};
int student::noofstudents=1;
int main()
{
student s;
cout<<s.number()<<endl;
cout<<student::number()<<endl;
//该代码中两种调用静态变量函数的意义一样。
return 0;
}
应当注意:静态成员不于任何对象联系,故不能对非静态成员进行默认访问 (但不是不能访问)
exp:
class student{
public:
static char* sname()//静态成员函数是所有成员共享的
{
cout<<noofstudents<<endl;
return name;//error,哪个对象?
}
protected:
static int noofstudents;
char name[40];
};
静态成员函数sname()只认类型,不认对象。若使用对象s引导的s.sname(),也只识别对象s所属类型。
静态成员的这种性质使得访问任何非静态成员的操作都是违法的。,所以上述代码中name对sname是未知类型的。
静态成员函数访问对象中非静态成员的方法
::静态成员函数于非静态成员函数的根本区别:
静态成员函数没有this指针。而非静态成员函数有一个指向当前对象的指针this。
友元
友元是一种定义在类外部的普通函数或类,但它需要在类体内进行说明,为了与该类的成员函数加以区别,在说明时前面加以关键字friend。友元不是成员函数,但是它可以访问类中的私有成员。