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