Nạp chồng phương thức khởi tạo trong C++ | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

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

Explanation:

  • name and gender are two private attributes of Student class.
  • Student() is the no-arg constructor which is used for initializing 2 values: name = "Unknown", gender = 'u'
  • Student(gender: char) is the parameterized constructor which is used for initializing values to 2 attributes gender and name (this.gender = gender, name = "Unknown").
  • Student(name: String, gender: char) is the parameterized constructor which is used for initializing values to 2 attributes name and gender.
  • display() method is used for displaying information of an object on the screen. If gender = 'm', display "Gender: Male" on the screen, if gender = 'f', display "Gender: Female" on the screen, if gender = 'u', display "Gender: Unknown" on the screen. See the example below:
    • If name = "Thu", gender = 'f', when we call the display() method, the screen will display as below:
      Name: Thu
      Gender: Female​
    • If name = "Sang", gender = 'u', when we call the display() method, the screen will display as below:
      Name: Sang
      Gender: Unknown
    • If name = "Unknown", gender = 'u', when we call the display() method, the screen will display as below:
      Name: Unknown
      Gender: Unknown​

A program to test the above Student class:

#include "Student.cpp"

int main() {
	Student s1;
	s1.display();
	Student s2("Quang");
	s2.display();
	Student s3('m');
	s3.display();
	Student s4("Thu", 'f');
	s4.display();
	return 0;
}

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

Name: Unknown
Gender: Unknown
Name: Quang
Gender: Unknown
Name: Unknown
Gender: Male
Name: Thu
Gender: Female

Instruction

You need to create a Student class as below:

#include<iostream>

using namespace std;

class Student {
private:
	string name;
	char gender;
public:
	Student() {
		name = "Unknown";
		gender = 'u';
	}

	Student(string name) {
		this->name = name;
		this->gender = 'u';
	}

	Student(char gender) {
		this->name = "Unknown";
		this->gender = gender;
	}

	Student(string name, char gender) {
		this->name = name;
		this->gender = gender;
	}

	void display() {
		cout << "Name: " + name << endl;
		if (gender == 'u') {
			cout << "Gender: Unknown" << endl;
		}
		if (gender == 'm') {
			cout << "Gender: Male" << endl;
		}
		if (gender == 'f') {
			cout << "Gender: Female" << endl;
		}
	}
};