静态私有变量在c++中不起作用

static private variables not working in c++

本文关键字:c++ 不起作用 变量 静态      更新时间:2023-10-16

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

#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 <<"nn";
}
void totalCount(){
    cout <<"Total Counts: "<< count <<"nn";
}
};
void main(){
KittyCat tech, review, article, photo, video;
tech.set(10, "Technology");
review.set(85, "Reviews");
article.set(54, "Articles");
article.show();
article.totalCount();
}

有什么想法吗?

偶数int KittyCat::count;也会起作用。静态数据成员的默认值为0。静态数据成员在类内声明,但在类定义外定义。

int KittyCat::count = 0;

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

得到这个:

#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 <<"nn";
}
void totalCount(){
    cout <<"Total Counts: "<< count <<"nn";
}
};
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();
}