Problem statement:
Implement a class called Student that has the following properties:
Two private integer data members: age and standard.
Two public member functions:
void set_age(int a): Sets the value of age to the given integer.
void set_standard(int s): Sets the value of standard to the given integer.
int get_age(): Returns the value of age.
int get_standard(): Returns the value of standard.
string to_string(): Returns a string in the format "age,standard".
Sample Input:
The input consists of two lines. The first line contains an integer representing the age, and the second line contains an integer representing the standard.
15
10
Sample Output:
Print the age and standard of the student using the to_string() member function.
15,10
Explanation:
In this example, the input represents a student who is 15 years old and is in the 10th standard. We create an instance of the Student class, set the age and standard using the member functions, and then print the age and standard using the to_string() member function.
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int age;
int standard;
public:
void set_age(int a) {
age = a;
}
void set_standard(int s) {
standard = s;
}
int get_age() {
return age;
}
int get_standard() {
return standard;
}
string to_string() {
return std::to_string(age) + "," + std::to_string(standard);
}
};
int main() {
int age, standard;
cin >> age >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
cout << st.to_string() << endl;
return 0;
}
Code Explanation
We define a class called Student with two private integer data members: age and standard.
The class also has four public member functions:
set_age(int a): Sets the value of age to the given integer.
set_standard(int s): Sets the value of standard to the given integer.
get_age(): Returns the value of age.
get_standard(): Returns the value of standard.
to_string(): Returns a string in the format "age,standard".
Inside the main() function, we read the input values for age and standard using cin.
We create an instance of the Student class called st.
We set the age and standard of the student using the set_age() and set_standard() member functions, respectively.
Finally, we print the age and standard of the student by calling the to_string() member function on the st object.
This solution demonstrates the usage of classes in C++ to encapsulate data and behavior into a single entity.
I hope this solution and explanation meet your requirements and are helpful for understanding the problem and its solution!