X
xgngli
Here I have four classes: RefBook and TextBook, which are inheritated
from base class Book; and a class Database, which has an array to store
the pointers to those two kinds of books. Now I am writing a member
function of Database, print(), which prints the information of all the
RefBooks in the array by using dynamic_cast. Below is my code(some
implemetations omitted). I don't know why the compiler complains that
"cannot dynamic_cast type Book* to type RefBook* (source type is not
polymophic)".
class Book
public:
Book(const string& = "");
const string& getName() const;
private:
string name_;
};
class RefBook : public Book {
public:
RefBook(const string&, char);
char getSubject() const;
void print() const;
private:
char subject_;
};
class TextBook : public Book {
public:
TextBook(const string&, int);
private:
int course_;
};
class Database {
public:
Database();
enum {SIZE = 100};
void addBook(Book*);
void printRef() const;
private:
Book* book_[SIZE];
int number_;
};
void Database:rintRef() const {
for(int i = 0; i < number_; i++)
// compiler complains "source type is not polymophic", what's
wrong?
if(RefBook* rb = dynamic_cast<RefBook*> (book_))
cout << rb->print() << endl;
}
int main() {
Book* a = new RefBook("Relativity Theory", 'p');
Book* b = new TextBook("Database Management", 113);
Database db;
db.addBook(a);
db.addBook(b);
db.printRef();
delete a;
delete b;
return 0;
}
from base class Book; and a class Database, which has an array to store
the pointers to those two kinds of books. Now I am writing a member
function of Database, print(), which prints the information of all the
RefBooks in the array by using dynamic_cast. Below is my code(some
implemetations omitted). I don't know why the compiler complains that
"cannot dynamic_cast type Book* to type RefBook* (source type is not
polymophic)".
class Book
public:
Book(const string& = "");
const string& getName() const;
private:
string name_;
};
class RefBook : public Book {
public:
RefBook(const string&, char);
char getSubject() const;
void print() const;
private:
char subject_;
};
class TextBook : public Book {
public:
TextBook(const string&, int);
private:
int course_;
};
class Database {
public:
Database();
enum {SIZE = 100};
void addBook(Book*);
void printRef() const;
private:
Book* book_[SIZE];
int number_;
};
void Database:rintRef() const {
for(int i = 0; i < number_; i++)
// compiler complains "source type is not polymophic", what's
wrong?
if(RefBook* rb = dynamic_cast<RefBook*> (book_))
cout << rb->print() << endl;
}
int main() {
Book* a = new RefBook("Relativity Theory", 'p');
Book* b = new TextBook("Database Management", 113);
Database db;
db.addBook(a);
db.addBook(b);
db.printRef();
delete a;
delete b;
return 0;
}