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

Dav*_*vid 3 c++

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

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)

Rem*_*eau 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");
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)


Pau*_*zie 7

另一种方法是使用大括号初始化器:

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

wordType object{"hello world"};
Run Code Online (Sandbox Code Playgroud)

实例

  • @GuillaumeRacicot:参见[Aggregate Initialization](http://en.cppreference.com/w/cpp/language/aggregate_initialization)和[List Initialization](http://en.cppreference.com/w/cpp/language/list_initialization ). (2认同)