Xin chào , cho em hỏi là khi con trỏ của lớp cơ sở tham chiếu đến các đối tượng của lớp dẫn xuất thì tại sao nó lại không truy cập được các hàm thành phần của lớp dẫn xuất ạ (có phải là do tính đóng gói không ạ) ? Và có cách nào để truy cập các hàm thành phần của lớp dẫn xuất trực tiếp hoặc gián tiếp từ con trỏ của lớp cơ sở không ạ ?
#include<iostream>
using namespace std;
class Media {
private :
string name;
long int price;
public :
Media(string name, long int price);
~Media(){
}
virtual void input();
virtual void output();
};
Media::Media(string name, long int price){
this->name = name;
this->price = price;
}
void Media::input(){
cout<<"Enter name : ";
cin>>name;
cout<<"Enter price : ";
cin>>price;
}
void Media::output(){
cout<<"Display name : "<<name<<endl;
cout<<"Display price : "<<price<<endl;
}
class Book :public Media{
private :
int page;
string author;
public :
Book(string name, long int price):Media(name, price){
this->page = 0;
this->author = "";
}
void input();
void output();
Book operator>(Book &);
};
void Book::input(){
Media::input();
cout<<"Enter page : ";
cin>>page;
cout<<"Enter author : ";
fflush(stdin);
getline(cin, author);
}
void Book::output(){
Media::output();
cout<<"Display page : "<<page<<endl;
cout<<"Display author : "<<author<<endl;
}
Book Book::operator>(Book &x){
return (this->page > x.page) ? *this : x;
}
int main(){
Media *p[3] ;
for(i =0; i<3; i++){
p[i] = new Book("name", 4500);
cout<<"Nhap gia tri cua phan tu thu "<<i<<" : ";
p[i]->input();
}
for(int i=0; i<3; i++){
p[i] = new Book("name", 4500);
for(int j=i; j<n; j++){
p[i]->operator>(p[j]); // không thể truy cập được hàm thầnh phần của lớp dẫn xuất
}
}
}