公有继承私有继承

//Point.h
#ifndef _POINT_H
#define _POINT_H
class Point{
	public:
		void initPoint(float x = 0, float y = 0){
			this->x = x;
			this->y = y; 
		}
		void move(float offX, float offY){
			x += offX;
			y += offY;
		} 
		float getX() const {
			return x;
		}
		float getY() const {
			return y;
		}
		
	private:
		float x, y;
};
#endif


//Rectangle.h
#ifndef _RECTANGLE_H
#define _RECTANGLE_H
#include "Point.h"
class Rectangle: public Point{ //派生类定义部分 
	public:
		void initRectangle(float x, float y, float w, float h){   //新增公有函数 
			initPoint(x, y);   //调用基类共有成员函数
			this->w = w;
			this->h = h; 
		} 
		float getH() const {
			return h;
		}
		float getW() const {
			return w;
		}
		
	private:
		float w, h;
}; 
#endif


/*公有继承*/ 
#include <iostream>
#include <cmath>
#include "Rectangle.h"
using namespace std;
int main(){
	Rectangle rect;
	rect.initRectangle(2, 3, 20, 10);
	rect.move(3, 2);
	cout <<"The data of rect(x, y, w, h): " << endl;
	cout << rect.getX() << ", " << rect.getY() << ", " << rect.getW() << ", " << rect.getH() << endl; 
	return 0;
}


/*私有继承*/ 
#include <iostream>
using namespace std;

class Point{
	public:
		void initPoint(float x = 0, float y = 0){
			this->x = x;
			this->y = y; 
		}
		void move(float offX, float offY){
			x += offX;
			y += offY;
		} 
		float getX() const {
			return x;
		}
		float getY() const {
			return y;
		}
		
	private:
		float x, y;
};
class Rectangle: private Point{ //派生类定义部分 
	public:
		void initRectangle(float x, float y, float w, float h){   //新增公有函数 
			initPoint(x, y);   //调用基类共有成员函数
			this->w = w;
			this->h = h; 
		} 
		void move(float offX, float offY){  
			Point::move(offX, offY); //私有继承而来的成员函数在类外不能直接访问,必须要在类里定义访问接口 
		}
		float getX() const {
			return Point::getX(); 
		}
		float getY() const{
			return Point::getY();
		}
		float getH() const {
			return h;
		}
		float getW() const {
			return w;
		}
		
	private:
		float w, h;
}; 


int main(){
	Rectangle rect;
	rect.initRectangle(2, 3, 20, 10);
	rect.move(3, 2);
	cout <<"The data of rect(x, y, w, h): " << endl;
	cout << rect.getX() << ", " << rect.getY() << ", " << rect.getW() << ", " << rect.getH() << endl; 
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wangjian530/article/details/80468228
今日推荐