我在创建以下类型的对象时遇到问题:
struct wordType
{
string word = "";
int count = 0;
};
wordType object("hello world");
我得到的错误是:
[Error] no matching function for call to 'wordType::wordType(std::string&)
答案 0 :(得分:7)
您正在尝试使用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");
或者,您可以在没有任何构造函数参数的情况下使用局部变量,然后再填充它:
struct wordType
{
string word = "";
int count = 0;
};
wordType object;
object.word = "hello world";
答案 1 :(得分:7)
另一种方法是使用大括号初始化器:
struct wordType
{
string word = "";
int count = 0;
};
wordType object{"hello world"};
答案 2 :(得分:4)
书写
wordType object("hello world");
告诉编译器您希望使用参数“hello”构造一个名为wordType
construct 的object
实例,但是您的类没有定义匹配的构造函数。
您的选择是使用统一初始化来成员初始化结构:
wordType object { "hello world" };
或添加匹配的构造函数:
#include <string>
struct wordType {
std::string word_ = "";
int count_ = 0;
// ... other ctors
wordType(const std::string& word) : word_(word) {}
};
int main() {
wordType object("hello world");
}
N.B
我建议你为你的类型(WordType)使用大写前缀,并使用成员变量的区别机制:我使用_
后缀,这样我就能告诉word_
是类型的成员,而word
是变量/参数。