单例模式思考:
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除外)