【发布时间】:2017-06-25 14:57:11
【问题描述】:
我写了下面这个简单的C++结构体实现来看看结构体指针的用法。
#include <iostream>
struct Employee
{
std::string name;
std::string sex;
int e_id;
}emp[2];
void printEmployee(struct Employee *e)
{
std::cout << e->name << std::endl;
std::cout << e->sex << std::endl;
std::cout << e->e_id << std::endl;
}
int main(int argc, char const *argv[])
{
struct Employee *e_ptr;
e_ptr = emp;
for (int i = 0; i < 2; ++i)
{
std::getline(std::cin, emp[i].name);
std::getline(std::cin, emp[i].sex);
std::cin >> emp[i].e_id;
}
for (int i = 0; i < 2; ++i)
{
printEmployee(e_ptr+i);
std::cout << std::endl;
}
return 0;
}
输入是
John Smith
male
123
Sarah Collin
female
在这些输入之后,程序会显示输出,尽管代码应该再接受一个输入。输出是
John Smith
male
123
Sarah Collin
0
但是,如果我不包括 int e_id 作为成员,那么代码就可以完美运行。
【问题讨论】: