Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符串常量之前应为标识符_C++_Linux_Constructor - Fatal编程技术网

C++ 字符串常量之前应为标识符

C++ 字符串常量之前应为标识符,c++,linux,constructor,C++,Linux,Constructor,有这样一个程序: #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; } 您不能在

有这样一个程序:

#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;
}

您不能在声明tst_u的地方初始化它。这只能对静态常量基元类型执行。相反,您需要为test1提供构造函数


编辑:下面是中的一个工作示例。注意我做的一些更改-首先,最好让test的构造函数对string进行const引用,以避免复制。第二,如果程序成功,您应该返回0而不是1(使用返回1,您会得到运行时错误)

还有另一种更简单的方法来做您想要做的事情:只需从
test tst(“Hi”)更改您的语句即可
测试tst{“Hi”}和它将工作。下面是修改后的代码,它按预期工作

#include <iostream>
#include <string>
using namespace std;
class test
{
public:
    test(std::string s):str(s){cout<<"str is: "<<s;}
private:
    std::string str;
};

class test1
{
public:
    test tst_{"Hi"};
};

int main()
{   test1 obj;
    return 0;
}
#包括
#包括
使用名称空间std;
课堂测试
{
公众:

test(std::string s):str(s){coutYou真的应该学会总是使用
g++-Wall-g
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
    test(std::string s):str(s){cout<<"str is: "<<s;}
private:
    std::string str;
};

class test1
{
public:
    test tst_{"Hi"};
};

int main()
{   test1 obj;
    return 0;
}