继承和派生是C++语言中最重要的一个特性,它涵盖了C++的精髓,是C++对于C语言的最大区别度,下面让我们一起来探讨一下吧!
-
继承与派生的简论:
-
派生类成员的访问属性:
实验1:
先建立一个Point类,包含数据成员x,y(坐标),函数成员void print()用于输出坐标点,如(1,2);以Point类为基类,派生出一个Circle类,增加数据成员raduis(半径),增加函数成员void print()用于输出圆心和半径、函数成员double area()用于计算圆的面积;在主函数中,定义对象来测试类的声明。
#include<iostream>
using namespace std;
//Point类:
class Point
{
public:
Point(int xx = 0,int yy = 0)
{
x = xx;
y = yy;
}
protected:
int x,y;
};
//派生类对Pointe基类进行访问(派生类的声明):
class Circle:public Point
{
public:
Circle(int xx = 0,int yy = 0,int rr = 0)
{
Point(xx,yy);
r = rr;
}
void area(void)
{
double s = 3.14*r*r;
cout<<s<<endl;
}
protected:
int r;
};
int main(void)
{
Circle cir(1,2,3);
cir.area();
return 0;
}
-
派生类的构造/析构函数:
-
多重继承&&基类和派生类间的转化:
实验2:
基类与派生类之间的转化及赋值举例。
#include<iostream>
using namespace std;
//基类:
class Base
{
int x;
public:
Base(){x=0;};
Base(int xx){x=xx;};
void print(){cout<<"x="<<x<<endl;}
};
//派生类:
class Derived:public Base
{
int y;
public:
Derived(){y=0;}
Derived(int xx,int yy):Base(xx){y=yy;}
void print(){cout<<"y="<<y<<endl;}
};
int main()
{
Base b1(10);
Derived d1(20,30);
b1.print();
d1.print();
cout<<endl;
Base &rb=b1;
Base &rd=d1;
Derived &r=d1;
rb.print ();
rd.print ();
r.print ();
cout<<endl;
Base *pb;
pb=&b1;
pb->print();
pb=&d1;
pb->print();
Derived *pd=&d1;
pd->print();
b1=d1;
b1.print();
return 0;
}