search

Home  >  Q&A  >  body text

class - c++ 类中的static 成员变量可以通过cin输入吗

如果可以,如何实现?

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


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

这两种方法都不行?

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

天蓬老师天蓬老师2802 days ago608

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:09:18

    #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

    reply
    0
  • 阿神

    阿神2017-04-17 12:09:18

    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;
    }

    reply
    0
  • Cancelreply