21xrx.com
2025-06-10 00:06:48 Tuesday
登录
文章检索 我的文章 写文章
如何在C++中返回一个结构体数组的函数
2023-07-08 22:06:28 深夜i     123     0
C++ 返回 结构体数组 函数

C++中的结构体是一种用于组织和存储相关数据的数据类型。在某些情况下,您可能需要从一个函数中返回一个结构体数组。这篇文章将介绍如何在C++中实现这个任务。

在C++中,您可以使用结构体来创建自定义数据类型。结构体可以包含多个数据类型的成员变量。下面是一个简单的结构体定义示例:

struct Contact
 string name;
 string email;
 int phone;
;

该结构体定义了一个名为Contact的数据类型,其中包括三个成员变量:name(名称)、email(电子邮件)和phone(电话)。

要返回一个结构体数组的函数,您需要执行以下步骤:

1. 定义结构体数组。首先需要定义一个结构体数组,并填充其成员变量。

Contact contacts[3];
contacts[0].name = "John";
contacts[0].email = "john@example.com";
contacts[0].phone = 1234567890;

2. 在函数中声明返回类型。在函数开头需要声明返回类型为结构体数组类型:

Contact[] myFunction()
 //函数体

3. 在函数中返回结构体数组。在函数体中,您可以使用return语句返回结构体数组:

Contact[] myFunction() {
 Contact contacts[3];
 contacts[0].name = "John";
 contacts[0].email = "john@example.com";
 contacts[0].phone = 1234567890;
 //继续填充数组中的其他结构体
 return contacts;
}

这些步骤将定义和填充结构体数组,并从函数中返回该数组。您可以在主函数中调用此函数以获取该数组,并使用数据。

下面是一个完整的示例代码:

#include <iostream>
#include <string>
using namespace std;
struct Contact
 string name;
 string email;
 int phone;
;
Contact[] getContacts() {
 Contact contacts[3];
 contacts[0].name = "John";
 contacts[0].email = "john@example.com";
 contacts[0].phone = 1234567890;
 contacts[1].name = "Jane";
 contacts[1].email = "jane@example.com";
 contacts[1].phone = 987654321;
 contacts[2].name = "Bob";
 contacts[2].email = "bob@example.com";
 contacts[2].phone = 5555555555;
 return contacts;
}
int main() {
 Contact[] myContacts = getContacts();
 for(int i = 0; i < 3; i++) {
  cout << "Name: " << myContacts[i].name << endl;
  cout << "Email: " << myContacts[i].email << endl;
  cout << "Phone: " << myContacts[i].phone << endl;
  cout << endl;
 }
 return 0;
}

此代码将定义一个名为Contact的结构体,并填充其成员变量。getContacts函数将返回一个包含三个Contact结构体的数组。主函数将调用getContacts函数以获取该数组并使用数据。输出结果将显示每个联系人的名称、电子邮件和电话。

  
  

评论区