如何在 c++ 11 中创建此结构的数组

How do I create an array of this struct in c++ 11?

本文关键字:结构 数组 创建 c++      更新时间:2023-10-16

我是 c++ 的新手,我想创建和数组下面的结构。请帮忙!谢谢

struct contact{
    string name;
    string address;
    string phone;
    string email;
    contact(string n, string a, string p, string e);
    };

问题似乎是您正在尝试实例化contact对象的数组,但此类没有默认构造函数,因为您添加了非默认的用户定义构造函数。这将删除编译器生成的默认构造函数。要取回它,您可以使用default

struct contact{
  string name;
  string address;
  string phone;
  string email;
  contact() = default; // HERE
  contact(string n, string a, string p, string e);
};

这允许您执行此类操作:

contact contactsA[42];
std::array<contacts, 42> contactsB;

编辑:鉴于类型的简单性,另一种解决方案是删除用户定义的构造函数。这将使类型成为聚合,这将允许您使用聚合初始化,并且您不必采取任何特殊操作来启用默认构造:

struct contact
{
  string name;
  string address;
  string phone;
  string email;
};

现在您可以使用聚合初始化:

contact c{"John", "Doe", "0123-456-78-90", "j.doe@yoyodyne.com"};

并像以前一样实例化数组:

contact contactsA[42];
std::array<contacts, 42> contactsB;

在C++中,如果您创建一个没有任何构造函数的类,编译器将为您创建一个简单的默认构造函数 - 即不带参数的构造函数。 由于你已创建非默认构造函数,因此编译器不会为你生成默认构造函数。 您通常会创建一个类型为"联系人"的数组,其中包含以下内容:

contact my_array[10];

这将在每个成员上调用联系人的默认构造函数。 由于没有默认构造函数,您可能会看到编译失败。

我建议添加一个默认构造函数。 您的新结构可能如下所示:

struct contact{
  string name;
  string address;
  string phone;
  string email;
  contact();  // This is your default constructor
  contact(string n, string a, string p, string e);
};

完成此操作后,您现在应该能够创建具有以下内容的数组:

contact my_array[10];
#include <vector>
#include <array>
#include <string>
using std::string;
struct contact{
  string name;
  string address;
  string phone;
  string email;
  contact(string n, string a, string p, string e);
};
std::vector<contact> contacts1;      // for an array without a size known at compile time.
std::array<contact, 1> contacts2 = { // for an array with a known and static size.
  contact{ "Bob Smith", "42 Emesgate Lane, Silverdale, Carnforth, Lancashire LA5 0RF, UK", "01254 453873", "bob@example.com"}
};