c++中的继承使用冒号(:),可以指定继承方式(private,protect,public),支持继承多个父类,要访问父类的同名函数,使用 父类::函数 的形式
看个例子:
#pragma once
#include <iostream>
using namespace std;
class parent1
{
private:
void test1() {}
public :
void test000() {
cout << "parent1" << endl;
}
void test2() {}
};
class parent2
{
private:
void test3() {}
public:
void test111() {
cout << "parent2" << endl;
}
void test4() {}
};
class child1:private parent1, public parent2
{
public:
void test000() {
cout << "child" << endl;
parent1::test000();
}
void test111() {
cout << "child" << endl;
}
private:
void testRange() {
cout << "testRange" << endl;
}
};
先测试下怎么调用父类方法:
child1 cd1;
cd1.test000();
结果:
child
parent1
再来看一下继承方式:


我们看以看到,在之类中调用父类的方法,和继承的方式无关,只和父类方法的作用域有关。如果是通过子类调用父类中的方法,看到例子中,cd1.test2()无法调用了,因为parent1的继承方式是private。
也就是说,如果是私有继承的话。父类中的公有(public)方法都被改为private了。外部是无法再访问的。对子类内部调用无影响
接下来看虚函数
我们修改一下调用方法

我们看到子类不能强转为私有继承的父类
我们改成公有继承的parent2
parent2* cd2 = new child1();
cd2->test111();
测试结果:
parent2
我们看到,调用的是parent2中的test111方法,这个和java中是不一样的。调用哪个方法和类的类型有关,试一下调用test000

可以看到,调用不了test000,因为parent2中没有这个方法。
如果要在调用test111的时候,调用子类中的test111,应该怎么做呢?这里就需要使用虚函数 virtual,我们把parent2中test11改为虚函数
virtual void test111() {
cout << "parent2" << endl;
}
执行结果
child
不使用虚函数的称为静态多态
使用虚函数的称为动态多态
可以看到,调用的是子类中的test111.如果想要实现java中abstract效果,可以使用纯虚函数,如下
virtual void test222() = 0;

可以看到,子类必须去实现这个方法,否则会报错
注意:
构造方法不能声明为虚函数,会报错
析构方法一般声明为虚函数,因为释放资源一般是在子类中
网友评论