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

函数接收const结构体参数时执行cin操作的编译与运行疑问

关于const参数修改的问题解答

嘿,这个问题问到点子上了——const关键字的核心意义就是强制保证参数的只读性,所以咱们直接说结论:这种情况会触发编译错误,根本到不了程序运行阶段。

具体拆解一下:

  • 当你给函数参数加上const修饰(比如const Student students[]),编译器会在编译阶段就对所有试图修改该参数的代码做严格检查。像你说的用cin给这个数组里的Student对象赋值,本质是在修改const对象的成员变量,这完全违反了const的只读约定,编译器会直接抛出错误,比如类似「assignment of member 'Student::xxx' in read-only object」的提示,直接终止编译流程。
  • 不存在“程序能运行但参数没被修改”的可能,因为const的约束是编译期生效的,编译器不会允许这种违规代码生成可执行文件。

举个直观的代码例子,你一看就懂:

#include <iostream>
#include <string>
using namespace std;

struct Student {
    string name;
    int age;
};

// 带const修饰的函数
void read_student(const Student students[], int size) {
    for (int i = 0; i < size; ++i) {
        // 下面这行代码会直接触发编译错误
        cin >> students[i].name >> students[i].age;
    }
}

int main() {
    Student class1[3];
    read_student(class1, 3);
    return 0;
}

这段代码连编译都通不过,更别说运行了。

如果你的函数确实需要修改传入的参数(比如读取数据到Student数组里),那正确的做法就是去掉参数的const修饰,让编译器允许对参数进行修改操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:50:02