0 先上代码
class Person {
private:
char *name;
int age;
char *work;
static int num;
public:
Person()
{
cout <<"Person()"<<endl;
this->name = "none";
this->work = "none";
this->age = 0;
this->num++;
}
Person(char *name, int age, char *work = "none")
{
cout <<"Person(char, int)"<<endl;
this->age = age;
this->name = new char[strlen(name) + 1];
strcpy(this->name, name);
this->work = new char[strlen(work) + 1];
strcpy(this->work, work);
this->num++;
}
~Person()
{
this->num--;
}
void printInfo(void)
{
cout <<"name "<< this->name <<", age = "<< this->age <<", work = "<< work <<endl;
}
static int getnum(void);
};
int Person::num = 0;
int Person::getnum(void)
{
return num;
}
int main(int argc, char **argv)
{
cout << "person num = "<<Person::getnum()<<endl;
Person per("xiaoming",10,"student");
cout << "person num = "<<Person::getnum()<<endl;
return 0;
}
1 什么是静态
static int num;这个是静态变量;
static int getnum(void);这个是静态方法
2 目的
比如上面代码中的这个静态变量,是用来记录一共创建了几个人的;
3 理解
该变量是出于类结构本身,不是属于任何一个创建的实体。
*比如这里在没有创建per时,就可以使用num 和getnum(void)方法了,
说明了他是属于类结构本身。
4 注意
int Person::num = 0;
int Person::getnum(void)
{
return num;
}
这里需要先定义和初始我们的静态变量和方法
网友评论