C++ 多重、多级和分层继承
在本教程中,我们将通过示例了解 C++ 编程中的不同继承模型:多重、多级和分层继承。
继承是面向对象编程语言的核心特性之一。它允许软件开发人员从现有类派生一个新类。派生类继承了基类的特性。
C++ 编程中有多种继承模型。
C++ 多级继承
在 C++ 编程中,不仅可以从基类派生类,还可以从派生类再次派生类。这种形式的继承称为多级继承。
class A {
... .. ...
};
class B: public A {
... .. ...
};
class C: public B {
... ... ...
};
在这里,类 B
派生自基类 A
,类 C
派生自派生类 B
.
示例 1:C++ 多级继承
#include <iostream>
using namespace std;
class A {
public:
void display() {
cout<<"Base class content.";
}
};
class B : public A {};
class C : public B {};
int main() {
C obj;
obj.display();
return 0;
}
输出
Base class content.
在这个程序中,类 C
派生自类 B
(它从基类 A
派生)。
在 main()
函数中定义了 C
类的对象 obj
。
当 display()
函数被调用时, 在 A
类中的 display()
被执行。这是因为类 C
和类 B
中没有 display()
函数.
编译器首先在类 C
中查找 display()
函数. 由于该函数在那里不存在,它在类 B
中查找该函数。
该函数也不存在于类 B
中 乙,所以编译器在类 A
中寻找它。
如果 display()
函数存在于 C
, 编译器覆盖了类 A
中的 display()
。
C++ 多重继承
在 C++ 编程中,一个类可以从多个父类派生。例如,Bat
类 派生自基类 Mammal
和 WingedAnimal
. 这是有道理的,因为蝙蝠是哺乳动物,也是有翼动物。
示例 2:C++ 编程中的多重继承
#include <iostream>
using namespace std;
class Mammal {
public:
Mammal() {
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
WingedAnimal() {
cout << "Winged animal can flap." << endl;
}
};
class Bat: public Mammal, public WingedAnimal {};
int main() {
Bat b1;
return 0;
}
输出
Mammals can give direct birth.
Winged animal can flap.
多重继承中的歧义
多重继承最明显的问题发生在函数覆盖期间。
假设,两个基类具有相同的函数,但在派生类中未被覆盖。
如果您尝试使用派生类的对象调用该函数,编译器将显示错误。这是因为编译器不知道要调用哪个函数。例如,
class base1 {
public:
void someFunction( ) {....}
};
class base2 {
void someFunction( ) {....}
};
class derived : public base1, public base2 {};
int main() {
derived obj;
obj.someFunction() // Error!
}
这个问题可以使用范围解析函数来解决这个问题,以指定要对哪个类中的函数进行调用:
int main() {
obj.base1::someFunction( ); // 调用 base1 类中的方法
obj.base2::someFunction(); // 调用 base2 类中的方法
}
C++ 分层继承
如果从基类继承了多个类,则称为分层继承。在分层继承中,子类中的所有共同特征都包含在基类中。
例如,Physics、Chemistry、Biology 都派生自 Science 类。同样,Dog、Cat、Horse 都派生自 Animal 类。
分层继承的语法
class base_class {
... .. ...
}
class first_derived_class: public base_class {
... .. ...
}
class second_derived_class: public base_class {
... .. ...
}
class third_derived_class: public base_class {
... .. ...
}
示例 3:C++ 编程中的分层继承
// C++ program to demonstrate hierarchical inheritance
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void info() {
cout << "I am an animal." << endl;
}
};
// derived class 1
class Dog : public Animal {
public:
void bark() {
cout << "I am a Dog. Woof woof." << endl;
}
};
// derived class 2
class Cat : public Animal {
public:
void meow() {
cout << "I am a Cat. Meow." << endl;
}
};
int main() {
// Create object of Dog class
Dog dog1;
cout << "Dog Class:" << endl;
dog1.info(); // Parent Class function
dog1.bark();
// Create object of Cat class
Cat cat1;
cout << "\nCat Class:" << endl;
cat1.info(); // Parent Class function
cat1.meow();
return 0;
}
输出
Dog Class:
I am an animal.
I am a Dog. Woof woof.
Cat Class:
I am an animal.
I am a Cat. Meow.
在这里, Dog
类和 Cat
类都是从 Animal
类派生的。因此,两个派生类都可以访问属于 Animal
该类的 info()
函数。