我无法理解为什么静态私有变量在我的代码中不起作用!这是代码:
#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();
}
有什么想法吗?
答案 0 :(得分:0)
甚至是int KittyCat :: count;本来也会奏效的。静态数据成员的默认值为0.静态数据成员在类中声明,但在类定义之外定义。
答案 1 :(得分:-1)
int KittyCat::count = 0;
必须在main之前添加,因为必须在使用前初始化所有静态数据成员。
答案 2 :(得分:-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();
}