范例一:统计产生对象的个数
class Demo{ // 定义 Person 类
private:
static int count = 0 ; // 所有对象共享此属性
public :
Demo(){
count++ ; // 只要有对象产生就应该自增
printf("产生了 %d个对象!",count) ;
}
};
void main(){
new Demo() ; // 增加新对象
new Demo() ; // 增加新对象
new Demo() ; // 增加新对象
};
范例二:自动编名操作
class Demo{ // 定义 Person 类
private :
String name ; // 保存名字
static int count = 0 ; // 所有对象共享此属性
public :
Demo(){
count++ ; // 有对象产生就自增
this->name = "DEMO-" + count ; // 自动进行编名操作
}
Demo(String name){
this->name = name; // 可以通过构造赋值
}
String getName(){ // 取得姓名
return this->name ;
}
};
void main(){
printf(new Demo().getName().c_str()) ;
printf(new Demo("LXH").getName().c_str()) ;
printf(new Demo().getName()) ;
printf(new Demo("MLDN").getName().c_str()) ;
printf(new Demo().getName().c_str()) ;
}