Linux 字符串常量前的预期标识符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10052135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
expected identifier before string constant
提问by rahman
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
g++ main.cpp
main.cpp:16:12: error: expected identifier before string constant
main.cpp:16:12: error: expected ‘,' or ‘...' before string constant
采纳答案by Ivaylo Strandjev
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.
你不能在你声明它的地方初始化 tst_ 。这只能对静态常量基本类型执行。相反,您将需要具有 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)
编辑:这是ideone.com 中的一个工作示例。请注意我所做的一些更改 - 首先最好让 test 的构造函数对 string 进行 const 引用以避免复制。第二 - 如果程序成功,你应该返回 0 而不是 1(返回 1 你会在ideone 中得到运行时错误)