C++类的对象成员不可以显式初始化[Error] expected identifier before string constant

    技术2024-08-02  68

    #include<string> #include<iostream> using namespace std; class B{ public: B(int a){} B(){} }; class A{ public: int i = 2020; const int ci = 2020; //基本数据类型可以 static int si; //初始化只能在类外 //static int si = 2021; //[Error] ISO C++ forbids in-class initialization of non-const static member 'A::si' static const int sci = 2022;// Right ,因为是静态基本类型常量 const string str; //在构造函数的初始化列表仍然可以初始化,不过构造函数体内不可以 static string sss; //string str("graduate"); //const string cstr("forth"); //static string sstr("graduate");//[Error] expected identifier before string constant,类内的对象不能显式调用非默认构造函数 //static const string scstr = "sdfdf";//[Error] in-class initialization of static data member 'const string A::scstr' of non-literal type B b;//如果B类没有默认构造函数,那么必须在A的构造函数初始化列表中显式初始化 A(): str("zyh"){ } }; int A::si = 10; string A::sss = "2030"; int main() { A ac; cout<<ac.str; return 0; }

    看代码注释,一目了然!

    Processed: 0.015, SQL: 9