【发布时间】:2018-09-08 05:02:03
【问题描述】:
- 据我所知,当函数接收到 const 参数,函数不能改变它。所以,应该怎么做 当函数应该更改参数时会发生什么? (例如 该函数包含对 const 参数的“cin”推荐)。将 是编译错误吗?或者它会运行但参数 在实践中不改变?
- 我尝试在下面的代码中做一些测试。当我从
void read_student (Student students[], int size)设置为void read_student (const Student students[], int size)时,我收到以下信息 错误消息(这些只是其中的一部分)。这是否发生 因为'const'参数和'cin'的组合 表彰?如果是,我应该如何理解 这些消息?
|19|错误:'operator>>' 不匹配(操作数类型是 'std::istream {aka std::basic_istream}' 和 'const char [20]')|
|19|错误:类型的非常量引用的无效初始化 'bool&' 来自 'bool' 类型的右值|
|19|错误:从“const char*”到“short int”的无效转换 [-fpermissive]|
|19|错误:无法绑定右值 '(short int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' 到 'short 整数&'|
|19|错误:从 'const char*' 到 'short unsigned 的无效转换 int' [-fpermissive]|
|19|错误:无法绑定右值'(short unsigned int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' 到 'short 无符号整数&'|
#include <iostream>
using namespace std;
const int max_students=3;
struct Student
{
char name [20];
float avg;
};
void read_student (const Student students[], int size) //const Student VS Student
{
for (int i=0; i<size; i++)
{
cout << "enter name and avg for student #" << i+1 << endl;
cin >> students[i].name >> students[i].avg;
}
}
void print_student (const Student students[], int size)
{
for (int i=0; i<size; i++)
cout << "name: " << students[i].name << "\taverage: " << students[i].avg <<endl;
}
int main()
{
Student students[max_students];
read_student(students, max_students);
cout << "ell students: \n";
print_student(students, max_students);
return 0;
}
【问题讨论】: