#include?<iostream.h>#include?<string.h>class?CStudent{public:CStudent(char?*n,?int?a);~CStudent();static?void?SetAge(int?age);private:char?*name;int?age;static?int?nTotalObj;};int?CStudent::nTotalObj?=?0;CStudent::CStudent(char?*n,?int?a):age(a){int?nLen?=?strlen(n);name?=?new?char[nLen+1];strcpy(name,n);name[nLen]?=?’\0’;nTotalObj++;}CStudent::~CStudent(){delete[]?name;nTotalObj--;}void?CStudent::SetAge(int?age){this->age?=?age;}void?main(){CStudent?stu1("張三",25);CStudent?str2("李四",26);cout<<"CStudent::nTotalObj="<<CStudent::nTotalObj<<endl;}
1 回答
已采納

asd8532
TA貢獻(xiàn)143條經(jīng)驗(yàn) 獲得超187個(gè)贊
使用靜態(tài)成員函數(shù)的目的就是使這個(gè)函數(shù)成為“類”級(jí)別的,而不是“對(duì)象級(jí)別”的,實(shí)際上相當(dāng)于必須通過這個(gè)類使用的全局函數(shù),是不屬于任何對(duì)象的,如果你感覺一個(gè)靜態(tài)成員函數(shù)需要處理對(duì)象,那么很可能是應(yīng)該把它定義為成員函數(shù)。靜態(tài)成員函數(shù)不能調(diào)用普通成員函數(shù)和使用普通成員變量。
void?CStudent::SetAge(int?age)
{
this->age?=?age;
}這個(gè)就不行
- 1 回答
- 0 關(guān)注
- 1978 瀏覽
添加回答
舉報(bào)
0/150
提交
取消