centos

CentOS下C++继承与多态如何实现

小樊
34
2025-08-16 17:42:28
栏目: 编程语言

在C++中,继承和多态是面向对象编程的两个重要特性。继承允许一个类从另一个类获取属性和方法,而多态允许我们以统一的接口处理不同的数据类型。以下是在CentOS环境下实现C++继承与多态的基本步骤:

1. 编写头文件

首先,创建一个头文件来定义基类和派生类。

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

2. 编写源文件

接下来,编写源文件来实现类的功能。

Base.cpp

#include "Base.h"

Derived.cpp

#include "Derived.h"

3. 编写主程序

最后,编写一个主程序来测试继承和多态。

main.cpp

#include "Base.h"
#include "Derived.h"

int main() {
    Base* basePtr;
    Derived derivedObj;

    basePtr = &derivedObj;

    basePtr->display(); // 调用派生类的display函数

    return 0;
}

4. 编译和运行

在CentOS终端中,使用g++编译器编译并运行程序。

g++ -o main main.cpp Base.cpp Derived.cpp
./main

解释

通过以上步骤,你可以在CentOS环境下实现C++的继承与多态。

0
看了该问题的人还看了