公有继承(public)
继承的访问控制 ①基类的public 和protected 成员:访问属性在派生类中保持不变 ; ②基类的private 成员:不可直接访问。 访问权限 ①派生类中的成员函数:可以直接访问基类中的public和protected 成员,但不能直接访问基类中的private成员; ②通过派生类的对象:只能访问public成员。
#include "Point.h"
#include "Rectangle.h"
int main ( )
{
Rectangle rect;
rect. initRectangle ( 2 , 3 , 20 , 10 ) ;
rect. move ( 3 , 2 ) ;
cout << "The data of rect(x,y,w,h):" ;
cout << rect. getX ( ) << ","
<< rect. getY ( ) << ","
<< rect. getW ( ) << ","
<< rect. getH ( ) << endl;
return 0 ;
}
#include "Point.h"
class Rectangle : public Point
{
public :
void initRectangle ( float , float , float , float ) ;
float getH ( ) const { return h; }
float getW ( ) const { return w; }
~ Rectangle ( ) ;
private :
float w, h;
} ;
#include "Rectangle.h"
void Rectangle:: initRectangle ( float x, float y, float w, float h)
{
initPoint ( x, y) ;
this - > w = w;
this - > h = h;
}
Rectangle:: ~ Rectangle ( )
{
cout << "Destructing Rectangle...\n" ;
}
#ifndef _POINT_H
#define _POINT_H
#include <iostream>
using namespace std;
class Point
{
public :
void initPoint ( float , float ) ;
void move ( float , float ) ;
float getX ( ) { return x; }
float getY ( ) { return y; }
~ Point ( ) ;
private :
float x, y;
} ;
#endif
#include "Point.h"
void Point:: initPoint ( float x = 0 , float y = 0 )
{
this - > x = x;
this - > y = y;
}
void Point:: move ( float offX, float offY)
{
x = x + offX;
y = y + offY;
}
Point:: ~ Point ( )
{
cout << "Destructing Point...\n" ;
}