-4

我不明白为什么静态私有变量在我的代码中不起作用!这是代码:

#include<iostream>
#include<string>
using namespace std;
class KittyCat{
private:
int a;
string t;
static int count;
public:
KittyCat(){
    a=0;
    t="NULL";
    count++;
}
void set(int i, string m){
    a=i;
    t=m;
}
void show(){
    cout << "A is: "<< a <<" T is: " << t <<"\n\n";
}
void totalCount(){
    cout <<"Total Counts: "<< count <<"\n\n";
}

};
void main(){
KittyCat tech, review, article, photo, video;
tech.set(10, "Technology");
review.set(85, "Reviews");
article.set(54, "Articles");
article.show();
article.totalCount();
}

有任何想法吗?

4

3 回答 3

0

甚至 int KittyCat::count; 也会奏效的。静态数据成员的默认值为 0。静态数据成员在类内声明,但在类定义之外定义。

于 2013-06-26T06:49:06.997 回答
-1
int KittyCat::count = 0;

必须在 main 之前添加,因为所有静态数据成员必须在使用前进行初始化。

于 2013-06-26T06:23:30.800 回答
-3

明白啦:

#include<iostream>
#include<string>
using namespace std;
class KittyCat{
private:
int a;
string t;
static int count;
public:
KittyCat(){
    a=0;
    t="NULL";
    count++;
}
void set(int i, string m){
    a=i;
    t=m;
}
void show(){
    cout << "A is: "<< a <<" T is: " << t <<"\n\n";
}
void totalCount(){
    cout <<"Total Counts: "<< count <<"\n\n";
}

};
int KittyCat::count=0;
void main(){
KittyCat tech, review, article, photo, video;
tech.set(10, "Technology");
review.set(85, "Reviews");
article.set(54, "Articles");
article.totalCount();
}
于 2013-06-26T06:07:05.060 回答