C++ method assignment

Asked

Viewed 38 times

0

#include <iostream>

using namespace std;

class Aluno{
    public:
    string nome;
    int idade;
    float n1;
    float n2;
    float media(float n1, float n2);
};

float Aluno::media(float n1, float n2){
    return (n1+n2)/2;
}

int main(){
    Aluno *aluno1;
    Aluno *aluno2;
    aluno1 = new Aluno();
    aluno2 = new Aluno();
    float media1, media2;

    aluno1->nome = "Igor";
    aluno1->idade = 19;
    aluno1->n1 = 3.0;
    aluno1->n2 = 4.5;

    aluno2->nome = "Walter";
    aluno2->idade = 19;
    aluno2->n1 = 5.5;
    aluno2->n2 = 2.5;

    media1 = aluno1->media(float n1, float n2);
    media2 = aluno2->media(float n1, float n2);

    cout << "Aluno: " << aluno1->nome << endl;
    cout << "Idade: " << aluno1->idade << endl;
    cout << "Média: " << media1 << endl;

    cout << "Aluno: " << aluno2->nome << endl;
    cout << "Idade: " << aluno2->idade << endl;
    cout << "Média: " << media2 << endl;

    return 0;

}

Right here:

media1 = aluno1->media(float n1, float n2);
media2 = aluno2->media(float n1, float n2);

The following error is occurring: "expected primary-expression before float"

2 answers

1

There’s an error in your code:

media1 = aluno1->media(float n1, float n2);
media2 = aluno2->media(float n1, float n2);

You don’t need to declare the type before using the function.

Switch to:

class Aluno{
    public:
    string nome;
    int idade;
    float n1;
    float n2;
    float media();
};

float Aluno::media(){
    return (n1+n2)/2;
}

You can use the properties of the Student object to calculate the average.

media1 = aluno1->media();
media2 = aluno2->media();

1

When you do:

media1 = aluno1->media(float n1, float n2);
media2 = aluno2->media(float n1, float n2);

You are doing two incompatible things, you are using an assignment, and a method definition. The correct one would be to define the average method in the student class, as you actually did, and in the main method just call this methods by passing the parameters:

media1 = aluno1->media(n1, n2);
media2 = aluno2->media(n1, n2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.