单例模式思考

 

单例模式思考:

class printer{
public:
    int num;

    static printer* getinstance(){
        return next;
    }
    
    void dayin(string str){
        cout<<str<<endl;
        num++;
    }
private:
    //单例模式中,构造方法是私有的属性
    printer(){
        this->num=0;
    }
    printer(const printer& p){
        
    }
    static printer* next;//指向printer类的静态成员变量的指针
};


printer* printer::next=new printer;


void test(){
    printer* p1=printer::getinstance();
    p1->dayin("hello1");
    p1->dayin("hello2");
    p1->dayin("hello3");
    p1->dayin("hello4");

    cout<<p1->num<<endl;
    p1->dayin("hello2");
    cout<<p1->num<<endl;
}
单例模式中,类只会创建一个对象,注意,类的构造函数必须是private类型,只能通过指针来操作

常函数:类的成员函数最后面加一个const限定符表示常函数,常函数不能用来修改类的成员属性;

 

class student{
public:
    student(){
        
    }
    void foo(int a){
        this->id=a;
        //this=NULL;   非法操作,this指针此时为指向类实例化对象的指针
        this->id=0;    //允许的操作,因为此时的this指针表示的是指针常量 student* const
    }
    void fooo(int a){ const
        //this->id=0;此时为非法操作,因为fooo函数为常函数,不允许修改成员属性const student* const 
    }
private:
    int id;
};


 常对象只能调用常函数,因为常对象不允许修改类的成员属性。(mutable除外)
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值