Bài tập C++ OOP: tạo lớp sách và tác giả | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create an Author class and a Book class with the information as in the following class diagram:

Explanation:

Author class

  • This class is used for storing information about the author of the book.
  • name, email attributes describe name and email address of the author.
  • Author(name: String, email: String) is the parameterized constructor which is used for initializing values to the corresponding attributes.
  • setName(), getName(), setEmail(), getEmail() are setters and getter.

Book class

  • This class is used for storing information about books. 
  • name, price, authors are attributes storing name, price and author of the book respectively.
  • Book(name: String, authors: Author[], price: double) is the parameterized constructor which is used for initializing values to the corresponding attributes.
  • setName(), getName(), setPrice(), getPrice() are setters and getters.
  • getAuthorNames() method returns the author names of the book in the following format "authorName1, authorName2, ..., authorNameN".

Notes: If you did not know about vector data type in C++, you could refer in "Standard library in C++" in codelearn system.

A program to test the above classes:

#include "Author.cpp"
#include "Book.cpp"

int main() {
	vector<Author> authors;
	authors.push_back(Author("Viet", "[email protected]"));
	authors.push_back(Author("Tuan", "[email protected]"));
	authors.push_back(Author("KienNT", "[email protected]"));

	Book book1("C++ for Beginners", authors, 210000);
	cout << book1.getAuthorNames();	
	return 0;
}

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

Viet, Tuan, Kien

Instruction

Code sample:

Author.cpp file

#pragma once
#include <iostream>

using namespace std;

class Author {
private:
	string name;
	string email;
public:
	Author(string name, string email) {
		this->name = name;
		this->email = email;
	}

	string getName() {
		return name;
	}

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

	string getEmail() {
		return email;
	}

	void setEmail(string email) {
		this->email = email;
	}
};

Book.cpp file

#include <iostream>
#include <vector>
#include "Author.cpp"

using namespace std;

class Book {
private:
	string name;
	double price;
	vector<Author> authors;

public:
	Book(string name, vector<Author> authors, double price) {
		this->name = name;
		this->price = price;
		this->authors = authors;
	}

	string getName() {
		return name;
	}

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

	double getPrice() {
		return price;
	}

	void setPrice(double price) {
		this->price = price;
	}

	string getAuthorNames() {
		string authorNames = "";
		for (int i = 0; i < authors.size() - 1; i++) {
			authorNames += authors[i].getName() + ", ";
		}
		authorNames += authors[authors.size() - 1].getName();
		return authorNames;
	}
};