静态数据成员与静态成员函数

静态数据成员与静态成员函数

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。友元不是成员函数,但是它可以访问类中的私有成员。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JdiLfc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值