在C++中,继承和多态是面向对象编程的两个重要特性。继承允许一个类从另一个类获取属性和方法,而多态允许我们以统一的接口处理不同的数据类型。以下是在CentOS环境下实现C++继承与多态的基本步骤:
首先,创建一个头文件来定义基类和派生类。
Base.h
#ifndef BASE_H
#define BASE_H
class Base {
public:
Base() {}
virtual ~Base() {} // 虚析构函数,确保派生类的析构函数被调用
virtual void display() const = 0; // 纯虚函数,使Base成为抽象类
};
#endif // BASE_H
Derived.h
#ifndef DERIVED_H
#define DERIVED_H
#include "Base.h"
#include <iostream>
class Derived : public Base {
public:
Derived() {}
~Derived() override {} // 派生类的析构函数
void display() const override { // 重写基类的纯虚函数
std::cout << "Derived class display function" << std::endl;
}
};
#endif // DERIVED_H
接下来,编写源文件来实现类的功能。
Base.cpp
#include "Base.h"
Derived.cpp
#include "Derived.h"
最后,编写一个主程序来测试继承和多态。
main.cpp
#include "Base.h"
#include "Derived.h"
int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display(); // 调用派生类的display函数
return 0;
}
在CentOS终端中,使用g++编译器编译并运行程序。
g++ -o main main.cpp Base.cpp Derived.cpp
./main
Derived
类继承自Base
类,使用public
继承方式。Base
类中的display
函数被声明为纯虚函数(= 0
),使Base
类成为抽象类。Derived
类重写了display
函数,实现了多态。virtual
关键字声明虚函数和虚析构函数,确保在通过基类指针删除派生类对象时,派生类的析构函数被正确调用。通过以上步骤,你可以在CentOS环境下实现C++的继承与多态。