jeudi 29 mars 2018

Function receiving a const struct and cin commend

  1. To the best of my knowledge, when a function receives a const parameter, the function cannot change it. so, what supposed to happen when the function should change the parameter? (For instance the function contains "cin" commend to the const parameter). Would it be compilation error? or would it run but the parameter don't change in practice?
  2. I tried to do some tests in the code below. When I set from void read_student (Student students[], int size) to void read_student (const Student students[], int size), I receive the following error messages (these are only some of them). Does this happen because the combination of the 'const' parameter and the 'cin' commend? If it is, how am I supposed to understand that from these messages?

|19|error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'const char [20]')|

|19|error: invalid initialization of non-const reference of type 'bool&' from an rvalue of type 'bool'|

|19|error: invalid conversion from 'const char*' to 'short int' [-fpermissive]|

|19|error: cannot bind rvalue '(short int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' to 'short int&'|

|19|error: invalid conversion from 'const char*' to 'short unsigned int' [-fpermissive]|

|19|error: cannot bind rvalue '(short unsigned int)((int)(&(students + ((sizetype)(((unsigned int)i) * 24u)))->Student::name))' to 'short unsigned int&'|

#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;
}

Aucun commentaire:

Enregistrer un commentaire