首页 > > 详细

讲解Colon Syntax、辅导c/c++程序语言、辅导Java,Python解析R语言编程|辅导Python程序

3.4 - Simple Inheritance
Exercise 1: Colon Syntax
The colon syntax can improve the performance of constructors. To test this, make sure that
you print some text in the point’s constructors, destructor and also the assignment operator.
Now, execute the following code in the test program and count the number of point
constructor, destructor and assignment calls:
Line l;
Now, change the constructors in the Line class to use the colon syntax to set the start- and
end-point data members and run the test program again. Is the number of point constructor,
destructor and assignment calls less than before?
Apply the colon syntax also for the Point class constructors and if applicable also for
the Circle class.
Exercise 2: Creating Shape Base Class
It can be useful to create a hierarchy of related classes using base- and derived classes.
• Classes are related (same family)
• Common data and functionality can be put in a base class.
• You can work with derived classes as if it is the base class.
In this exercise we are going to transform the Point and Line class into a Shape hierarchy as
shown in Figure 1.
+ToString()
Point
+ID()
+ToString()
-m_id
Shape
+ToString()
Line
+ToString()
Circle
Figure 1: Shape Hierarchy
First create a Shape base class.
• Add a source- and header file for a Shape class.
• Add a data member for an id number of type int.
• Add a default constructor that initializes the id using a random number. You can use
the rand() function from the “stdlib.h” header file.
• Add a copy constructor that copies the id member.
• Add an assignment operator that copies the id member.
• Add a ToString() function that returns the id as string e.g. “ID: 123”.
• Add an ID() function the retrieve the id of the shape.
Next the Point and Line classes (and the Circle class if applicable) must derive from Shape.
• Add the Shape class in the inheritance list of the Point, Line and optionally
the Circle class.
• The constructors of the Point, Line and optionally the Circle class should call the
appropriate constructor in the Shapebase class.
• The assignment operator should call the assignment operator of the Shape base
class. Otherwise the shape data will not be copied.
• Finally add code to the main program to test inheritance:
Shape s; // Create shape.
Point p(10, 20); // Create point.
Line l(Point(1,2), Point(3, 4)); // Create line.
cout<

联系我们 - QQ: 99515681 微信:codinghelp
程序辅导网!