class - c++ 类中的static 成员变量可以通过cin输入吗
天蓬老师
天蓬老师 2017-04-17 12:07:18
0
2
554

如果可以,如何实现?

比如,Student类中有一个满分标准是需要用户输入的
Class Student{
int static StandardFullScore;
}
貌似
cin >> Student :: StandardFullScore;


构建一个对象后Student s;
然后 cin >> s.StandardFullScore;

这两种方法都不行?

是不是本来这么做就是不可以的呢?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
伊谢尔伦
#include<iostream>
using namespace std;

class Demo{
  public: 
  int a;
  static int c;
};


static int b;
int main(){
  
 Demo d=Demo();
 cin>>b;
 cout<<"b="<<b<<endl;
 cin>>d.a;
 cout<<"the result="<<d.a<<endl;
 //cin>>Demo::c; //error
 //cout<<"c="<<Demo::c<<endl; //error
 //Demo::c=3; //error
 //int Demo::c=3; //ok
 
 d.a=3; //ok
 //cout<<"c="<<Demo::c<<endl; //error
 return 0;
}

First of all, C++ stipulates that static member variables of a class must be declared in the class and defined outside the class. As you can see from the comment above, the assignment statement is called directly

Demo::c=3

is wrong, the compiler prompts that it does not know the type of c. Let’s look at why the input cin>>Demo.c doesn’t work. We can know that the internal conversion is first into basic_istream(cin,&c), but at this time the compiler does not I don’t know what type the static member variable c is, and the traits attribute cannot be successfully specialized, so the call fails.

Then, the alternative here is to enter a variable and then set it through assignment or member functionStudent:: StandardFullScore;That’s it

阿神

I suspect that the questioner simply forgot to define a static variable. Static variables are declared in the class. If you only declare undefined but do not call it, there will be no problem. However, if the variable is undefined and used, a compilation error will occur. .

#include <cstdio>
#include <iostream>
using namespace std;

class zz{
public:
    static int b;//声明静态变量
};
int zz::b;//定义静态变量

int main()
{
    cin>>(zz::b);//正常使用
    cout<<(zz::b);
    return 0;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!