C++中的继承、派生
请帮我列出3~5个继承和派生的例子,以便帮我能更好的理解。
请帮我列出3~5个继承和派生的例子,以便帮我能更好的理解。
答案:c++继承经典例子
#include <iostream.h>class Base
{
private:
int b_number;
public:
Base( ){}
Base(int i) : b_number (i) { }
int get_number( ) {return b_number;}
void print( ) {cout << b_number << endl;}
};class Derived : public Base
{
private:
int d_number;public:
// constructor, initializer used to initialize the base part of a Derived object.
Derived( int i, int j ) : Base(i), d_number(j) { };
// a new member function that overrides the print( ) function in Base
void print( )
{
cout << get_number( ) << " ";
// access number through get_number( )
cout << d_number << endl;
}
};int main( )
{
Base a(2);
Derived b(3, 4);cout << "a is ";
a.print( ); // print( ) in Base
cout << "b is ";
b.print( ); // print( ) in Derived
cout << "base part of b is ";
b.Base::print( ); // print( ) in Basereturn 0;
}
没有虚析构函数,继承类没有析构
//Example: non- virtual destructors for dynamically allocated objects.#include <iostream.h>
#include <string.h>class Thing
{ public:
virtual void what_Am_I( ) {cout << "I am a Thing.\n";}
~Thing(){cout<<"Thing destructor"<<endl;}
};class Animal : public Thing
{
public:
virtual void what_Am_I( ) {cout << "I am an Animal.\n";}
~Animal(){cout<<"Animal destructor"<<endl;}
};void main( )
{
Thing *t =new Thing;
Animal*x = new Animal;
Thing* array[2];array[0] = t; // base pointer
array[1] = x;for (int i=0; i<2; i++) array->what_Am_I( ) ;
delete array[0];
delete array[1];
return ;
}
纯虚函数,多态#include <iostream.h>
#include <math.h>class Point
{
private:
double x;
double y;
public:
Point(double i, double j) : x(i), y(j) { }
void print( ) const
{ cout << "(" << x << ", " << y << ")"; }
};class Figure
{
private:
Point center;
public:
Figure (double i = 0, double j = 0) : center(i, j) { }
Point& location( )
{
return center;
} // return an lvalue
void move(Point p)
{
center = p;
draw( );
}virtual void draw( ) = 0; // draw the figure
virtual void rotate(double) = 0;
// rotate the figure by an angle
};class Circle : public Figure
{
private:
double radius;
public:
Circle(double i = 0, double j = 0, double r = 0) : Figure(i, j), radius(r) { }
void draw( )
{
cout << "A circle with center ";
location( ).print( );
cout << " and radius " << radius << endl;
}
void rotate(double)
{
cout << "no effect.\n";
} // must be defined
};class Square : public Figure
{
private:
double side; // length of the side
double angle; // the angle between a side and the x-axis
public:
Square(double i = 0, double j = 0, double d = 0, double a = 0) : Figure(i, j), side(d), angle(a) { }
void draw( )
{
cout << "A square with center ";
location( ).print( );
cout << " side length " << side << ".\n"
<< "The angle between one side and the X-axis is " << angle << endl;
}
void rotate(double a)
{
angle += a;
cout << "The angle between one side and the X-axis is " << angle << endl;
}
&
上一个:c++中字符串能简单相加吗?
下一个:如何学习编程,比如C++