我在创建以下类型的对象时遇到问题:
struct wordType
{
string word = "";
int count = 0;
};
wordType object("hello world");
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
[Error] no matching function for call to 'wordType::wordType(std::string&)
Run Code Online (Sandbox Code Playgroud)
您正在尝试wordType使用没有的构造函数构造对象wordType.您可以将该构造函数添加到您的代码中:
struct wordType
{
string word = "";
int count = 0;
wordType() = default;
wordType(const wordType&) = default;
wordType(const string &aword) : word(aword) {} // <-- here
};
wordType object("hello world");
Run Code Online (Sandbox Code Playgroud)
或者,您可以在没有任何构造函数参数的情况下使用局部变量,然后将其填充:
struct wordType
{
string word = "";
int count = 0;
};
wordType object;
object.word = "hello world";
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用大括号初始化器:
struct wordType
{
string word = "";
int count = 0;
};
wordType object{"hello world"};
Run Code Online (Sandbox Code Playgroud)