为什么我不能使用此构造函数参数构造此用户定义类型的对象?

时间:2016-09-19 18:54:24

标签: c++

我在创建以下类型的对象时遇到问题:

struct wordType 
{
   string word  = "";
   int    count = 0;
};

wordType object("hello world");

我得到的错误是:

[Error] no matching function for call to 'wordType::wordType(std::string&) 

3 个答案:

答案 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"};

Live Example

答案 2 :(得分:4)

书写

wordType object("hello world");

告诉编译器您希望使用参数“hello”构造一个名为wordType construct object实例,但是您的类没有定义匹配的构造函数。

您的选择是使用统一初始化来成员初始化结构:

wordType object { "hello world" };

现场演示:http://ideone.com/tDJ1kj

或添加匹配的构造函数:

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

现场演示:http://ideone.com/KVt238

N.B

我建议你为你的类型(WordType)使用大写前缀,并使用成员变量的区别机制:我使用_后缀,这样我就能告诉word_是类型的成员,而word是变量/参数。

相关问题