c++打印对象和构造函数
c++ printing object and constructor
大家好,我在最后一个循环中运行以下程序时遇到了问题,它只打印三个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)
element
是Info
数组中元素的副本。你忙着填写这份复印件,然后它就被丢弃了。Info
的内容保持不变,四周都是空字符串。
让它
for(Employee& element:Info)
相关文章:
- 对象实例化调用构造函数的次数太多
- Arduino C++在构造函数中用参数声明对象数组
- 模板,函数使用错误的构造函数来复制我的对象
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 通过构造函数创建的所有对象都具有相同的向量
- 是什么让放置新调用对象的构造函数?
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++ 对象指针数组的复制构造函数
- 在构造函数中输入对象时C++类成员作用域
- C++:将初始化的对象传递给另一个类的构造函数;需要不必要的构造函数吗?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- 如何将我编写的对象传递到另一个类的构造函数中?
- 使用向量初始化参数化构造函数的对象数组
- 在C++中将对象从另一个类传递到另一个类的构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 构造函数对象赋值是否泄漏内存
- gcc中不可移动构造函数对象的std::函数