Having a program like this:
#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 am I getting the following when I execute
g++ main.cpp
main.cpp:16:12: error: expected identifier before string constant
main.cpp:16:12: error: expected ‘,’ or ‘...’ before string constant
You can not initialize
tst_where you declare it. This can only be done forstatic constprimitive types. Instead you will need to have a constructor forclass test1.EDIT: below, you will see a working example I did in ideone.com. Note a few changes I did. First, it is better to have the constructor of
testtake aconstreference tostringto avoid copying. Second, if the program succeeds you shouldreturn 0not1(withreturn 1you get a runtime error in ideone).