expected identifier before string constant

时光怂恿深爱的人放手 提交于 2021-02-07 05:16:45

问题


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

回答1:


You can not initialize tst_ where you declare it. This can only be done for static const primitive types. Instead you will need to have constructor for test1.

EDIT: here is a working example in ideone.com. Note a few changes I did - first it is better to have the constructor of test take a const reference to string to avoid copying. Second - if the program succeeds you should return 0 not 1(with return 1 you get runtime error in ideone)



来源:https://stackoverflow.com/questions/10052135/expected-identifier-before-string-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!