C++ 将结构转换为类?
假设我们通过创建一个类AddressBook来创建一个地址簿。我们在类中放置了各种工具,包括添加成员的选项。如果我们使用一个结构来跟踪每个人的信息,它将如下所示:C++ 将结构转换为类?,c++,class,structure,C++,Class,Structure,假设我们通过创建一个类AddressBook来创建一个地址簿。我们在类中放置了各种工具,包括添加成员的选项。如果我们使用一个结构来跟踪每个人的信息,它将如下所示: class AddressBook { public: AddressBook() { count = 0; } void AddPerson(); //More functions.. struct Entry_Structure { c
class AddressBook {
public:
AddressBook()
{
count = 0;
}
void AddPerson();
//More functions..
struct Entry_Structure
{
char firstName[15];
char lastName[15];
char idNumber[15];
};
Entry_Structure entries[100];
unsigned int count;
};
然后我们可以为AddPerson函数编写以下代码:
void AddressBook::AddPerson()
{
cout << "Entry number " << (count + 1) << " : " << endl;
cout << "Enter subject's first and last name: ";
cin >> entries[count].firstName >> entries[count].lastName;
cout << "Please enter the subject's ID number: ";
cin >> entries[count].idNumber;
++count;
}
void AddressBook::AddPerson()
{
无法输入项[count]。idNumber;
++计数;
}
但是,对于条目结构
,我没有使用结构,而是使用了类
也就是说,class Entry\u Structure
而不是struct Entry\u Structure
我必须在程序和下面的函数中更改什么才能使其工作?类和结构之间唯一的实际区别是,默认情况下,类成员是私有的,
结构成员是公共的
因此:
相当于:
class Entry_Structure
{
public:
char firstName[15];
char lastName[15];
char idNumber[15];
};
class
和struct
之间唯一的实际区别是,默认情况下,类成员是private
,而struct
成员是public
因此:
相当于:
class Entry_Structure
{
public:
char firstName[15];
char lastName[15];
char idNumber[15];
};
另一个区别是继承在默认情况下对于结构是公共的:但它是类中的一个类,因此条目\结构条目[100]的工作方式不一样。@NaomiJacobson为什么不一样呢?不,结构数组的工作方式与类数组的工作方式完全相同。另一个区别是,默认情况下,结构的继承是公共的:但它是类中的一个类,所以Entry_Structure entries[100]的工作方式不一样。@NaomiJacobson为什么不一样?不,结构数组与类数组的工作方式完全相同。请使用std::string作为名称。“Hugh Fearnley Whittingstall”(英国名厨)的姓氏对于您的领域来说太长了。请使用std::string作为姓名。“Hugh Fearnley Whittingstall”(英国名厨)的姓氏对你的领域来说太长了。