C++继承与派生小例
声明一个Point作为基类,私有成员一个坐标int x,y;再声明一个point的方式为私有继承的Rectangle派生类,最后声明一个方式为公有继承的Cube的派生类,因为私有继承不可以直接访问基类的私有成员,基类的公有成员和保护成员都以私有成员身份出现在派生类中(公有继承时,基类的公有成员和保护成员的访问属性再派生类中不变,基类私有方式还是不可直接访问),这三个类的之间的链接到底是怎么实现的呢,Point---->Rectangle(私有继承)---->Cube(公有继承);
先声明一个Point类作为最底层的基类:
<span style="font-size:10px;">#ifndef __POINT_H__
#define __POINT_H__
#include <iostream>
using namespace std;
class Point
{
public:
Point(Point& p){
cout << "copy constructor called." << endl;
x = p.x;
y = p.y;
}
Point(){
x = 0;
y = 0;
}
Point(int x1, int y1){
this->x = x1; // x=x1;
this->y = y1;
cout << "constructor called." << endl;
}
~Point(){
//cout << "deleted." << endl;
}
protected:
void setX(int xx){
x = xx;
}
void setY(int yy){
y = yy;
}
public:
int getX();
int getY(){return this->y;}//类里实现,内敛函数
private:
//int x,y;};int Point::getX(){ //类外接口return x;}#endif //__POINT_H__
#pragma once
class Rectangle : private Point{
public:
Rectangle(float x, float y, int w, int h):Point(x,y),W(w),H(h){
}
Rectangle(){
W = 0;
H = 0;
}
public:
void Display(){
cout << "Position:(" << getX() << "," << getY() << ") " << W << " " << H << endl;
}
void UpdatePoint(int xx, int yy){
setX(xx);
setY(yy);
}
private:
int W,H;
};#pragma once
class Cube : public Rectangle{
public:
Cube(int x, int y, int w, int h, int l):Rectangle(x,y,w,h),L(l){
}
void Move (int x ,int y){
UpdatePoint(x,y);
}
private:
int L;
};</pre><pre name="code" class="cpp">//2.cpp注释 文件级
#include <iostream>
#include <cstring>
#include "point.h"
#include "rectangle.h"
#include "cube.h"
using namespace std;
int main()
{
Cube cube(3,4,10,5,30);
cube.Display();
cube.Move(23, 20);
cube.Display();
return 0;
}
此时:
//2.cpp注释 文件级
#include <iostream>
#include <cstring>
#include "point.h"
#include "rectangle.h"
#include "cube.h"
using namespace std;
int main()
{
Cube cube(3,4,10,5,30);
cube.Display();
cube.Move(23, 20);
cube.Display();
cout<<endl;
cout<<"Point存储的内存大小为:"<<sizeof(Point)<<endl<<"Rectangle存储的内存大小为:"<<sizeof(Rectangle)<<endl<<"Point存储的内存大小为:"<<sizeof(Cube)<<endl;
return 0;
}
详情看代码,分析参数的变化。

浙公网安备 33010602011771号