初探C++ 类的静态成员

如果一个变量是类的一部分,但却不是类的各个对象的一部分,则称它为static静态成员。

 

一个static成员只有唯一的一份副本,而不像非static成员那样在每个对象里各有一份副本。与此类似,一个需要访问类成员,不需要指定特定对象去调用的函数,也被称为static成员函数。

 

静态成员(包括函数和数据成员)在类里面声明后,都必须在某个地方另行定义。见如下实例:

 

 

#include <iostream>
using namespace std;

class hello
{
private:
    int times;
    static hello default_t;  //无法直接初始化
public:
    hello(int _t = default_t.times):times(_t){};
    static void set_default(int);
    void print();
};

void hello::print()
{
    for(int i=0;i!=times;i++)
        cout<<"hello"<<endl;
}

void hello::set_default(int _t)    //另行定义,不用再写static
{
    default_t.times = _t;
}

hello hello::default_t(4);         //另行定义


int main(int argc, char* argv[])
{
    //hello::set_default(5);
    //hello hello_world(2);
    hello hello_world;
    hello_world.print();

    return 0;
}


在类里声明静态整形常量

 

#include <iostream>
using namespace std;

class hello
{
private:
    int times;
    static const int default_t = 5;
public:
    hello(int _t = default_t):times(_t){};
    void print();
};

void hello::print()
{
    for(int i=0;i!=times;i++)
        cout<<"hello"<<endl;
}


int main(int argc, char* argv[])
{

    //hello hello_world(2);
    hello hello_world;
    hello_world.print();

    return 0;
}


 

静态内置类型与例1相似

#include <iostream>
using namespace std;

class hello
{
private:
    int times;
    static int default_t ;
public:
    hello(int _t = default_t):times(_t){};
    static void set_default(int);
    void print();
};

void hello::print()
{
    for(int i=0;i!=times;i++)
        cout<<"hello"<<endl;
}

void hello::set_default(int _t)
{
    hello::default_t = _t;
}

int hello::default_t = 3;

int main(int argc, char* argv[])
{

    //hello hello_world(2);
    //hello::set_default(10);
    hello hello_world;
    hello_world.print();

    return 0;
}


 


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值