Class Book
{
char* title;//Title
int num_pages;//Pages
char * writer;//author name
Public
Book (char* the_title, int pages, const char* the_writer): num_pages (pages)
{
title = new Char[strlen (the_title) + 1];
strcpy (title, the_title);
writer = new Char[strlen (the_writer) + 1];
strcpy (writer, the_writer);
}
~book ()
{
Delete[] title;
Delete[] writer;
}
int numofpages () const
{
return num_pages;
}
/* First, concept
When the const is in front of the function name, the function return value is decorated, after the function name is a regular member function,
The function cannot modify any members within an object, only read operations can occur, and write operations cannot occur.
Second, the principle:
We all know that when calling a member function, the compiler passes the address of the object itself as a hidden parameter to the function.
In the const member function, you can neither change the object that this is pointing to nor change the address that this is saved in.
The type of this is a const pointer to the Const type object. */
Const char* Thetitle () const
{
return title;
}
Const char* Thewriter ()
{
return writer;
}
};
Class Teachingmaterial:p ublic Book
{
char * course;
Public
Teachingmaterial (char* the_title, int pages, char* the_writer, const char* the_course)
: Book (The_title,pages,the_writer)
{
Course = new Char[strlen (the_course) + 1];
strcpy (course, the_course);
}
~teachingmaterial ()
{
Delete[] Course;
}
Const char* Thecourse () const
{
return course;
}
};
int _tmain ()
{
Teachingmaterial A_book ("C + + language programming", 299, "Zhang San", "Object-oriented Programming");
cout << "Textbook Name:" << a_book.thetitle () << Endl;
cout << "pages:" << a_book.numofpages () << Endl;
cout << "Author:" << a_book.thewriter () << Endl;
cout << "Related courses:" << a_book.thecourse () << Endl;
}
Definition and inheritance of simple classes