问题导入
#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;
}
此时会得到一个错误: error: expected identifier before string constant
在stackoverflow上的回答是: 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 a constructor for class test1.
下面的两种方法都可行
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const std::string& s):str(s){};
private:
std::string str;
};
class test1
{
public:
test1() : tst_("Hi") {} //
test tst_;
};
int main()
{
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const std::string& s):str(s){};
private:
std::string str;
};
class test1
{
public:
test tst_{"Hi"};
// 或者 test tst_ = test("Hi");
};
int main()
{
return 0;
}
类内初始化只可以使用{}或者=