如何在 c++ 11 中创建此结构的数组
How do I create an array of this struct in c++ 11?
我是 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"}
};
相关文章:
- C++将文本文件中的数据读取到结构数组中
- JSON转换为nlohmann JSON-lib中的结构数组
- 需要帮助将结构数组传递给函数
- 在 64 位边界上对齐C++结构数组?
- 带有枚举方向/类型的气泡排序结构数组
- 在C++中访问结构数组中的数据
- 从指向结构数组的指针中提取元素
- 如何制作一个地图,其中的值是C++中的结构数组
- 如何在函数中显示结构数组
- 包含作为成员C++函数的结构数组
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- std::transform 将一个结构数组复制到另一个结构数组
- 将非托管结构数组封送到托管数组
- 显示结构数组
- 结构数组中所有类似字段的总和
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 在 glsl opengl 中将嵌套结构数组作为统一传递
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 如何将字符串字符与结构数组进行比较?
- C++结构数组