I have been trying to make the string name;
private. I left the correct font below without putting the "string name"; in particular. Well, all attempts failed to put the "string name; private. Does anyone know how I could do this correctly. I'm new to C++ and object-oriented programming.
#include <iostream>
#include <string>
using namespace std;
class Aluno
{
I would like to put string nome;
in private, but it is not the same other functions
public:
string nome;
void setIda(int age)
{
if (age > 0 && age < 60)
idade = age;
else
idade = 0;
}
int getIda()
{
return idade;
}
void setMatr(int matr)
{
if (matr > 0 && matr <= 1000)
matricula = matr;
else
matricula = 0;
}
int getMatr()
{
return matricula;
}
I would like call string nome;
here
private:
int matricula;
int idade;
};
However, how could I call the functions string nome;
in the int main()?
int main()
{
Aluno *novo_aluno1 = new Aluno();
Aluno *novo_aluno2 = new Aluno();
novo_aluno1->nome = "John Smith";
novo_aluno1->setIda(32);
novo_aluno1->setMatr(999);
novo_aluno2->nome = "Mary Smith";
novo_aluno2->setIda(21);
novo_aluno2->setMatr(998);
cout << "\nNome: " << novo_aluno1->nome << "\n";
cout << "Idade: " << novo_aluno1->getIda() << "\n";
cout << "Matricula: " << novo_aluno1->getMatr() << "\n";
cout << "\nNome: " << novo_aluno2->nome << "\n";
cout << "Idade: " << novo_aluno2->getIda() << "\n";
cout << "Matricula: " << novo_aluno2->getMatr() << endl;
return 0;
}
A private parameter is only accesible from the class it is declared in. If you want to be able to get or set the information stored in a private field you have to make what we call (public) getters and setters methods.
private:
std::string nome;
public:
std::string get_nome()
{
return this->nome;
}
void set_nome(std::string var)
{
this->nome = var;
}
Then your setters and getters can be called in main()