Definition and inheritance of simple classes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.