字符串常量前的预期标识符 [英] expected identifier before string constant
问题描述
具有这样的程序:
#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
推荐答案
您不能在声明它的位置初始化tst_.这仅适用于静态const基本类型.相反,您将需要具有test1的构造函数.
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.
这是 ideone.com 中的一个有效示例.请注意我所做的一些更改-首先,最好让test的构造函数对字符串使用const引用以避免复制.第二-如果程序成功,则应返回0而不是1(返回1会在 ideone 中出现运行时错误)
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)
这篇关于字符串常量前的预期标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!