Bài tập C++ OOP: tạo các setter và getter | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Student class in Student.cpp file with the following information:

Explanation:

  • id, name, age, address, score attributes describe the ID, name, age, address and score respectively of a student where the score is guaranteed to be greater than 0 and less than or equal to 10 (if score < 0, assign 0 to score, if score > 10, assign 10 to score).
  • Student() is the no-arg constructor.
  • Student(id: int, name: String, age: int, adderss: String, score: int) is parameterized constructor used to initialize values to the following attributes id, name, age, address, score
  • The other methods are setter and getter.

A program to test the above Student class:

#include<iostream>
#include "Student.cpp"

using namespace std;

int main() {
	Student s(1001, "Trung", 24, "Ha Noi", 5);
	cout << s.getId() << endl;;
	cout << s.getName() << endl;;
	cout << s.getAge() << endl;;
	cout << s.getAddress() << endl;;
	cout << s.getScore() << endl;;
	s.setScore(-7);
	cout << s.getScore() << endl;;
	s.setScore(15);
	cout << s.getScore() << endl;;
	return 0;
}

When the above code is compiled and executed, it produces the following result:

1001
Trung
24
Ha Noi
5
0
10

Instruction

You need to create a Student class as below:

#include<iostream>
using namespace std;
class Student {
private:
	int id;
	string name;
	int age;
	string address;
	int score;
public:
	Student() {

	}

	Student(int id, string name, int age, string address, int score) {
		this->id = id;
		this->name = name;
		this->age = age;
		this->address = address;
		this->setScore(score);
	}

	int getId() {
		return id;
	}

	void setId(int id) {
		this->id = id;
	}

	string getName() {
		return name;
	}

	void setName(string name) {
		this->name = name;
	}

	int getAge() {
		return age;
	}

	void setAge(int age) {
		this->age = age;
	}

	string getAddress() {
		return address;
	}

	void setAddress(string address) {
		this->address = address;
	}

	int getScore() {
		return score;
	}

	void setScore(int score) {
		if (score < 0) {
			this->score = 0;
		} else if (score > 10) {
			this->score = 10;
		} else {
			this->score = score;
		}
	}
};