Chương trình 6.7 minh hoạ việc truy nhập đến các thành phần trùng nhau trong các lớp cơ sở và được định nghĩa lại trong lớp dẫn xuất.

Một phần của tài liệu Bài giảng Ngôn ngữ lập trình C++: Phần 2 - TS. Nguyễn Duy Phương (Trang 26 - 29)

được định nghĩa lại trong lớp dẫn xuất.

Chương trình 6.7 #include<stdio.h> #include<stdio.h> #include<conio.h> #include<string.h> /* Định nghĩa lớp Car */ class Car{ int speed; // Tốc độ

char mark[20]; // Nhãn hiệu float price; // Giá xe

public:

Car(); // Khởi tạo không tham số Car(int, char[], float); // Khởi tạo đủ tham số

void show(); // Giới thiệu float getSpeed(){return speed;};

char[] getMark(){return mark;}; float getPrice(){return price;}; };

Car::Car(){ speed = 0; strcpy(mark, “”); price = 0;

// Khởi tạo không tham số

}

// Khởi tạo đủ tham số

Car::Car(int speedIn, char markIn[], float priceIn){ speed = speedIn; strcpy(mark, markIn); price = priceIn; } // Giới thiệu void Car::show(){

cout << “This is a ” << mark << “ having a speed of ”

<< speed << “km/h and its price is $” << price << endl; return;

}

/* Định nghĩa lớp PublicTransport */ class PublicTransport{

float ticket; // Giá vé phương tiện public:

PublicTransport(float); void show();

float getTicket(){return ticket;};

// Khởi tạo đủ tham số // Giới thiệu

};

PublicTransport::PublicTransport(){ ticket = 0;

// Khởi tạo không tham số

}

// Khởi tạo đủ tham số

PublicTransport::PublicTransport(float ticketIn){ ticket = ticketIn;

}

// Giới thiệu

void PublicTransport::show(){

cout << “This public transport had a ticket of $” << ticket << endl;

return; } (adsbygoogle = window.adsbygoogle || []).push({});

/* Định nghĩa lớp Bus kế thừa từ lớp Car và PublicTransport */ class Bus: public Car, public PublicTransport{ // Thứ tự khai báo

int label; // Số hiệu tuyến xe public:

Bus(); // Khởi tạo không tham số Bus(int, char[], float, float, int);// Khởi tạo đủ tham số void show(); // Giới thiệu

};

// Khởi tạo không tham số

Bus::Bus(): Car(), Transport(){ // Theo thứ tự dẫn xuất label = 0;

// Khởi tạo đủ tham số

Bus::Bus(int sIn, char mIn[], float pIn, float tIn, int lIn):

Car(sIn, mIn, pIn), PublicTransport(tIn){ // Theo thứ tự dẫn xuất label = lIn;

}

Giới thiệu void Bus::show(){

cout << “This is a bus on the line ” << label “, its speed is ” << getSpeed() “km/h, mark is ” << getMark() “, price is $” << getPrice()

“ and ticket is ” << getTicket() << endl; return;

}

// phương thức main void main(){

clrscr();

Bus myBus(100, “Mercedes”, 3000, 1.5, 27);

myBus.Car::show(); myBus.PublicTransport:: show(); myBus.show(); return; // Hàm của lớp Car // Hàm của lớp PublicTransport // Hàm của lớp Bus }

Một phần của tài liệu Bài giảng Ngôn ngữ lập trình C++: Phần 2 - TS. Nguyễn Duy Phương (Trang 26 - 29)