You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++实现Employee类read、output函数及内存分配使用问题求助

问题修正点

  • 首先移除read()和output()成员函数多余的形参:这两个是类的成员函数,可以直接访问类内的name、age、department属性,不需要额外传参
  • 存储多个员工需要创建长度为n的Employee动态数组,而非单个对象
  • 先遍历数组调用每个元素的read()方法完成数据录入,再遍历数组调用每个元素的output()方法完成数据输出
  • 动态数组使用完毕后要调用delete[]释放内存,避免内存泄漏

修改后完整代码

#include <iostream>
#include <iomanip>

using namespace std;

class Employee
{
public:
    string name, department;
    int age;

    // 移除多余参数
    void output()
    {
        cout << name << endl;
        cout << "Age: " << age << " years" << endl;
        cout << "Department: " << department << endl << endl;
    }

    // 移除多余参数
    void read()
    {
        cout << "Enter last name and first name:";
        cin >> name;

        cout << "Enter age:";
        cin >> age;

        cout << "Enter department:";
        cin >> department;
    }
};

int main() {
    int n;
    cout << "Enter number of employees: ";
    cin >> n;
    // 创建动态数组存储n个员工
    Employee* employees = new Employee[n];

    // 读入所有员工数据
    for (int i = 0; i < n; i++) {
        cout << "\n=== 输入第" << i+1 << "个员工信息 ===" << endl;
        employees[i].read();
    }

    // 输出所有员工数据
    cout << "\n=== 所有员工信息如下 ===" << endl;
    for (int i = 0; i < n; i++) {
        employees[i].output();
    }

    // 释放动态数组内存
    delete[] employees;
    return 0;
}

内容的提问来源于stack exchange,提问作者Phonzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 06:06:04