C++静态成员对象与静态成员函数

静态成员对象

        1.该静态成员对象是属于类的,而非某个对象。

        2.该静态成员对象为类的所有对象所共享一份

        3.该静态成员不占用类对象的空间。

静态成员函数

class 类名
{
    public:
        static 返回值 函数名(形参列表)
        {
            //静态成员函数的函数体
            //静态成员函数体中只能访问类中的静态数据,不可以访问类中非静态数据。
            //因为static修饰的成员函数没有的this指针。所以不可调用类中的非静态数据。 
        }
};

        static修饰的成员函数并非修饰函数的存储形式,修饰的是成员函数的级别,这个级别就是此将成员函数提升为一个真正带有全局作用域的函数。

        只不过此函数是隐藏在类的作用域之中而已。

        所以此时该成员函数也就没有this指针。

        所以此函数不能调用类中的非静态属性或方法。

        此函数是为了整个类而服务的,而非某个对象,不依赖于对象的调用,可以直接使用类域 : : 调用。

例:

创建类:

#include <iostream>
using namespace std;
class Stu
{
private:
    string name;
    int age;
    static int count;
public:
    Stu(string name, int age)
    {
        this->name = name;
        this->age = age;
        count++;
        cout << "Stu的构造" << endl;
    }
    //2.返回本对象。
    const Stu setName(string name)
    {
        this->name = name;
        return *this;
    }
    string getName()const
    {
        return this->name;
    }
    int getAge()const
    {
        return this->age;
    }
    static int get_Count()
    {
        return count;
    }
    void showName()const
    {
        cout << this->name << endl;
    }


    ~Stu()
    {
        cout << "Stu的析构" << endl;
    }


    Stu(const Stu& other)
    {
        this->name = other.name;
        this->age = other.age;
        cout << "Stu的拷贝构造" << endl;
    }
};

        类外对静态变量初始化:

//静态全局变量类外初始化
int Stu::count = 0;

        全局函数:

void showInfo(const Stu& stu)
{
    cout << "姓名:" << stu.getName() << ",年龄:" << stu.getAge() << endl;
}

        主函数:

int main()
{
    Stu stu("zhangsan",18);
    showInfo(stu);
    stu.setName("lisi").showName();
    cout << "-------------" << endl;

    Stu* stu2 = new Stu("zhangsan",20);
    stu2->setName("lisi");
    stu2->showName();
    delete stu2;
    cout << "------------------" << endl;
    
    cout << Stu::get_Count() << endl;   //2,    一共创建了两个对象

    return 0;
}

        运行结果:

        

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值