您的位置:首页 > 编程语言 > C语言/C++

继承

2016-07-23 07:21 288 查看
继承总结

简单点来说就是代码基类(也可以称为父类)的代码在派生类(也可以称为子类)复制一样,子类中有父类的所有代码。

代码表示:

#include<iostream>

using namespace std;

class A            //基类

{

public:

void fun()

{

cout <<"this is fun():"<<endl;

}

};

class B: public A   //子类

{

public:

print()

{

cout << "this is print()"<<endl;

}

};

int main()

{

B b;

b.fun();    //调用基类

b.print();  //调用子类

return 0;

}

继承的几个注意点:

1.如果父类是私有的,则子类不能访问。

2.子类是公有继承,可以访问父类的公有,不能访问保护和私有成员。

3.子类是保护继承,父类中的公有在子类中升级为保护成员,私有还是私有,对象不能访问。

4.子类是私有继承,父类中的公有和保护在子类中升级为私有成员,私有还是私有,对象不能访问。

5.如果在父类和子类中出现相同的函数,则父类的函数会被隐藏,以下由代码实现:

#include<iostream>

using namespace std;

class A            //基类

{

public:

void fun()

{

cout <<"this is fun():"<<endl;

}

void print()

{

cout << "this is  A"<<endl;

}

 

};

class B: public A   //子类

{

public:

print()

{

cout << "this is print(B)"<<endl;

}

};

int main()

{

B b;

   

b.print();  //打印结果为this is print(B),说明父类被隐藏

return 0;

}

6.构造函数和析构函数

构造函数执行的顺序是先父后子,析构函数是按顺序执行的。

由代码实现:

#include<iostream>

using namespace std;

class A            //基类

{

public:

A()

{

cout << "this is A():"<<endl;

}

~A()

{

cout <<"this is ~A()"<<endl;

}

};

class B: public A   //子类

{

public:

B()

{

cout << "this is print(B)"<<endl;

}

~B()

{

cout <<"this is ~B:"<<endl;

}

};

int main()

{

B b;

   

return 0;

}

运行结果:



 

7.虚基类

在子类和父类中都有相同的函数名,虚拟继承及可以访问子类,否则访问父类。

 

观察代码及运行结果

#include<iostream>

using namespace std;

class A            //基类

{

public:

virtual fun()

{

cout <<"this is A fun()"<<endl;

}

};

class B: public A   //子类

{

public:

fun()

{

cout << "this is B fun()" <<endl;

}

 

};

int main()

{

B b;

    b.fun();

return 0;

}



 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  继承 c++