【发布时间】:2018-02-26 02:02:58
【问题描述】:
我正在尝试创建一个联系人类的空对象数组。从一个空数组开始,我想在 AddrBook.cpp 中创建一个函数,将 Contact 的对象添加到对象数组中,称为 addressBook。
我是否在 AddrBook.h 中正确初始化了数组?
如何检查某个联系人的对象是否存在于特定索引处?
AddrBook.cpp
#include "AddrBook.h"
namespace address_book_test
{
const int CAPACITY = 5;
void AddrBook::addContact(Contact& itemToAdd) // Add Contact to the AddrBook (using Contact object)
{
for (int i = 0; i < CAPACITY; i++)
{
if (/*Contact object does not exist at i*/)
{
/*Add Contact object*/
return;
}
}
return;
}
...
}
AddrBook.h
#ifndef ADDR_BOOK_H
#define ADDR_BOOK_H
#include <fstream>
using namespace std;
#include "Contact.h"
namespace address_book_test
{
class AddrBook
{
public:
static const int CAPACITY = 5;
// CONSTRUCTOR
AddrBook() { used = 0; }
// Modification Member Functions
void addContact(Contact& itemToAdd); // Add Contact to the AddrBook (using Contact object)
...
private:
static Contact addressBook[CAPACITY]; // The array used to store Contact objects
int used; // How much of addressBook is used
};
}
#endif
联系人.cpp
#ifndef CONTACT_H
#define CONTACT_H
#include <fstream>
using namespace std;
#include "Address.h"
#include "Name.h"
namespace address_book_test
{
class Contact
{
public:
// Constructor
Contact(string inLastName = "",
string inFirstName = "",
string inStreetAddress = "",
string inCity = "",
string inState = "",
string inZip = "",
string inPhone = "",
string inEmail = "",
string inBirthday = "",
string inPictureFile = "")
{
Name(inLastName, inFirstName);
Address(inStreetAddress, inCity, inState, inZip);
setPhone(inPhone);
setEmail(inEmail);
setBirthday(inBirthday);
setPictureFile(inPictureFile);
}
...
private:
Name fullName;
Address fullAddress;
string phone;
string email;
string birthday;
string pictureFile;
};
}
#endif
【问题讨论】:
-
数组有固定的大小。你不能有一个空数组。它总是有精确的
CAPACITY元素数量。如果您需要更改大小,请使用std::vector。 -
i位置已存在对象。您唯一能做的就是用副本覆盖它。
标签: c++ arrays object initialization