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

如何关联头文件数组与C++类,通过索引设置并打印对象名称?

解决方案:通过索引设置C++类的first_name属性

原代码问题梳理

  1. setFirst_name仅接受string类型参数,无法直接传入索引值,类型不匹配导致编译错误
  2. 类成员变量first_name与函数内赋值的First_name大小写不一致,C++区分大小写,会引发未定义变量错误
  3. getFirst_name被错误传入参数,原设计是无参数返回属性值,调用方式不符合函数定义
  4. 源文件未包含定义字符串数组的头文件,无法访问First数组

修改后完整代码

头文件(示例命名为names.h)

#include <string>
// 定义全局字符串数组,设为const避免意外修改
const std::string First[] = {"Jack", "Jill"};
// 计算数组长度,用于后续索引边界检查
const int NAME_COUNT = sizeof(First) / sizeof(First[0]);

源文件

#include <iostream>
#include "names.h"
using namespace std;

class Thing{
private:
    string first_name;
public:
    // 保留原string参数版本,兼容原有调用逻辑
    void setFirst_name(string First){
        first_name = First;
    }

    // 新增索引参数版本,实现通过索引设置名称
    void setFirst_name(int index){
        // 边界检查,防止越界访问数组
        if(index >= 0 && index < NAME_COUNT){
            first_name = First[index];
        } else {
            first_name = "";
            cerr << "错误:索引" << index << "超出有效范围" << endl;
        }
    }

    // 无参数返回当前first_name值
    string getFirst_name(){
        return first_name;
    }
};

int main() {
    Thing Obj;
    Obj.setFirst_name(1); // 传入索引1,对应数组中的"Jill"
    cout << Obj.getFirst_name() << endl; // 直接调用get方法返回结果
    return 0;
}

关键修改说明

  • 重载setFirst_name:新增接受int类型索引的函数版本,同时保留原string参数版本,兼顾两种调用场景
  • 修正变量名大小写:统一使用first_name作为成员变量名,避免编译错误
  • 添加索引边界检查:防止传入无效索引导致数组越界,提升代码健壮性
  • 正确引入头文件:确保源文件能访问到全局字符串数组First
  • 规范getFirst_name调用:该函数仅负责返回对象当前的first_name属性,无需传入参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:05:29