Expected identifier to string constant

Having such a program:

#include <iostream> #include <string> using namespace std; class test { public: test(std::string s):str(s){}; private: std::string str; }; class test1 { public: test tst_("Hi"); }; int main() { return 1; } 

... why do I get the following on execution

g ++ main.cpp

 main.cpp:16:12: error: expected identifier before string constant main.cpp:16:12: error: expected ',' or '...' before string constant 
+8
c ++ constructor linux
source share
1 answer

You cannot initialize tst_ where you declare it. This can only be done for primitive static const types. Instead, you'll need a constructor for test1.

EDIT: here is a working example at ideone.com . Pay attention to some changes that I made - at first it is better that the test constructor accepts a const reference to a string in order to avoid copying. Second - if the program succeeds, you should return 0 not 1 (with a return of 1 you will get a runtime error in ideone )

+15
source share

All Articles