c++打印对象和构造函数

c++ printing object and constructor

本文关键字:构造函数 对象 打印 c++      更新时间:2023-10-16

大家好,我在最后一个循环中运行以下程序时遇到了问题,它只打印三个0而不显示任何结果,我不确定程序出了什么问题,也许它与构造函数有关,但是当我在第二个最后一个循环中使用setter方法编写getter方法时,它会显示正确的结果。如有任何帮助,不胜感激。

#ifndef EMPLOYEE_H_INCLUDED
#define EMPLOYEE_H_INCLUDED
#include<string>
using namespace std;
class Employee
{
   private:
    string name;
    int idnumber;
    string department;
    string position;
   public:
     Employee(string ,int ,string ,string);
     void setName(string );
     void setDepartment(string);
     void setPosition(string);
     void setIDNumber(int);
     string getName() const
     {
         return name;
     }
     string getDepartment() const
     {
         return department;
     }
     string getPosition() const
     {
         return position;
     }
     int getIDnumber() const
     {
         return idnumber;
     }
};
#include "Employee.h";
#include <iostream>
#include <iomanip>
using namespace std;
Employee::Employee(string name ,int IDNumber ,string department ,string position)
{
   name=name;
   idnumber=IDNumber;
   department=department;
   position=position;
}
void Employee::setDepartment(string Department)
{
   department=Department;
}
void Employee::setName(string Name)
{
    name=Name;
}
void Employee::setPosition(string Position)
{
    position=Position;
}
void Employee::setIDNumber(int Number)
{
    idnumber=Number;
}

  int main()
  {
    string name;
    int IDNumber;
    string department;
    string position;
    const int Item=3;
    Employee info1("  ",0,"  ","  ");
    Employee info2("  ",0,"  ","  ");
    Employee info3("  ",0,"  ","  ");
    Employee Info[Item]={info1,info2,info3};
  }
  for(Employee element:Info)
  {
      cout<<"please enter your name "<<endl;
      cin>>name;
      element.setName(name);
      cout<<element.getName()<<endl;
      cout<<"please enter your department "<<endl;
      cin>>department;
      element.setDepartment(department);
      cout<<element.getDepartment()<<endl;
      cout<<"please enter your position"<<endl;
      cin>>position;
      element.setPosition(position);
      cout<<element.getPosition()<<endl;
      cout<<"please enter your IDNumber"<<endl;
      cin>>IDNumber;
      element.setIDNumber(IDNumber);
      cout<<element.getIDnumber()<<endl;
  }
  for(Employee element:Info)
  {
    cout<<element.getName()<<setw(8)<<element.getDepartment()   
    cout<<setw(8)<<element.getPosition()<<setw(8)<<element.getIDnumber()<<endl;
  }

}

for(Employee element:Info)

elementInfo数组中元素的副本。你忙着填写这份复印件,然后它就被丢弃了。Info的内容保持不变,四周都是空字符串。

让它

for(Employee& element:Info)