c++类中怎么使用static成员变量,请详细解答
以下代码运行时出现错误#include<cstdio>#include<cstring>#include<map>#include<list>#include<strin...
以下代码运行时出现错误
#include <cstdio>#include <cstring>#include <map>#include <list>#include <string>#include <iostream>#define maxn 1000010using namespace std;class test{public: static int a; test(int x):b(x){} void print() { cout<<b<<endl; }private: int b;};int main(){ int test::a=12; test c(23); cout<<c.a<<" "<<endl; c.print(); return 0;} 展开
#include <cstdio>#include <cstring>#include <map>#include <list>#include <string>#include <iostream>#define maxn 1000010using namespace std;class test{public: static int a; test(int x):b(x){} void print() { cout<<b<<endl; }private: int b;};int main(){ int test::a=12; test c(23); cout<<c.a<<" "<<endl; c.print(); return 0;} 展开
2个回答
展开全部
类的静态变量要放在类外初始化。
#include <iostream>
#define maxn 1000010
using namespace std;
class test
{
public:
static int a;
test(int x):b(x){}
void print()
{
cout<<b<<endl;
}
private:
int b;
};
int test::a=12; // 在类外初始化
int main()
{
test c(23);
cout<<c.a<<" "<<endl;
c.print();
return 0;
}
追问
非常感谢的
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询