Answer the question
In order to leave comments, you need to log in
Likbez. Variables for C++ classes?
Good afternoon. Such a situation, is it possible to store variables used in one class without initializing them outside the class?
For example:
int a;
Class n1;
n1.func1(a);
n1.func2(a);
Answer the question
In order to leave comments, you need to log in
Yes, you can. In this case, such a variable will be called a class property .
class Students {
// Имя студента
std::string name;
// Фамилия
std::string last_name;
// Пять промежуточных оценок студента
int scores[5];
// Итоговая оценка за семестр
float average_ball;
};
Variables in a class can be public, private or protected. In your case, I advise you to use private ones and set them through the constructor or set methods. and to pull out through the get methods.
For example:
#include <iostream>
class rabbit
{
public:
rabbit(int value)
{
m_value = value;
}
void SetValue(int value)
{
m_value = value;
}
int GetValue()
{
return m_value;
}
private:
int m_value;
};
int main()
{
rabbit mrRabbit(10);
std::cout << mrRabbit.GetValue();
mrRabbit.SetValue(100);
std::cout << mrRabbit.GetValue();
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question