C++ 静态私有变量在c++;

C++ 静态私有变量在c++;,c++,static,C++,Static,我不明白为什么静态私有变量在我的代码中不起作用!代码如下: #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=

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

#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();
}
#包括
#包括
使用名称空间std;
基蒂卡特班{
私人:
INTA;
字符串t;
静态整数计数;
公众:
基蒂卡特{
a=0;
t=“空”;
计数++;
}
无效集(整数i,字符串m){
a=i;
t=m;
}
无效显示(){
你能明白这一点吗

#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();
}
#包括
#包括
使用名称空间std;
基蒂卡特班{
私人:
INTA;
字符串t;
静态整数计数;
公众:
基蒂卡特{
a=0;
t=“空”;
计数++;
}
无效集(整数i,字符串m){
a=i;
t=m;
}
无效显示(){
库特

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

即使int KittyCat::count;也可以工作。静态数据成员的默认值为0。静态数据成员在类内声明,但在类定义外定义。

而不是(或除此之外)“不工作”,最好说明您期望的行为以及您观察到的行为。@Navin,不,默认情况下,“count”初始化为0。您声明了
count
,但从未定义过它。在
KittCat
的定义之后,但在
main
@Navin之前,添加一行类似于
int KittyCat::count;
,作为第二个time,静态变量默认初始化为0!@user1764961这就是我说的…我提到的“initialize”一词是错误的,应该是“define”。就像jerry的例子。这应该是什么?你能至少解释一下问题是什么吗?你能评论一下你的问题是否与可能重复的问题描述的问题相同吗?程序运行并报告了
总计数:5
。我觉得不错。你的期望是什么?什么“不起作用”对你来说?这不是回答问题的正确方式,特别是如果是你自己的问题。初始化是个好主意,但考虑到问题评论中的讨论,你本可以对这个答案多考虑一点。
int KittyCat::count = 0;