Bài tập C++ OOP: cài đặt lớp Student theo sơ đồ lớp cho trước | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

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

Explanation:

  • name, age, gender, gpa are private attributes that describe the name, age, gender and GPA of a student respectively.
  • Student(name: String, age: int, gender: String, gpa: double) is the parameterized constructor which is used to initialize values to attributes (assign name attribute to name parameter, assign age attribute to age parameter,...).
  • display() is the method displays information of student on the screen. For example, there are attributes that describe a student: name = "Quang", age = 24, gender = "Male", gpa = 7.7, when display() method is called, the program will produce the following result:
    Name: Quang
    Age: 24
    Gender: Male
    GPA: 7.7​

A program that tests Student class:

#include "student.cpp"

int main() {
    Student s("Quang", 24, "Male", 7.7);
    s.display();
}

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

Name: Quang
Age: 24
Gender: Male
GPA: 7.7

Theory

As in the previous lesson, if the name of input parameter is the same as the attribute name of the class, you can access the class's attribute by using this pointer as in the following example:

#include<iostream>

using namespace std;

class Student {
    string name;
    int age;
public:
    Student(string name, int age) {
        this->name = name;
        this->age = age;
    }
    void display() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    Student s("Linh", 24);
    s.display();
    return 0;
}

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

Name: Linh
Age: 24

Instruction

You need to create a Student class as below:

#include<iostream>

using namespace std;

class Student {
    string name;
    int age;
    string gender;
    double gpa;
public:
    Student(string name, int age, string gender, double gpa) {
        this->name = name;
        this->age = age;
        this->gender = gender;
        this->gpa = gpa;
    }
    void display() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "Gender: " << gender << endl;
        cout << "GPA: " << gpa << endl;
    }
};