在C++中,繼承和多態是面向對象編程的兩個核心概念。以下是在CentOS環境下實現繼承和多態的基本步驟:
定義基類: 基類是派生類的父類,它定義了一些公共的屬性和方法。
// Base.h
#ifndef BASE_H
#define BASE_H
class Base {
public:
Base() {}
virtual ~Base() {} // 虛析構函數,確保派生類的析構函數被調用
virtual void display() const {
std::cout << "Display Base" << std::endl;
}
};
#endif // BASE_H
定義派生類: 派生類繼承基類的屬性和方法,并可以添加新的屬性和方法。
// Derived.h
#ifndef DERIVED_H
#define DERIVED_H
#include "Base.h"
class Derived : public Base {
public:
Derived() {}
~Derived() override {}
void display() const override {
std::cout << "Display Derived" << std::endl;
}
void derivedFunction() const {
std::cout << "Derived Function" << std::endl;
}
};
#endif // DERIVED_H
多態允許你使用基類的指針或引用來調用派生類的方法。
使用基類指針調用派生類方法:
#include <iostream>
#include "Base.h"
#include "Derived.h"
int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
// 調用派生類的display方法
basePtr->display(); // 輸出: Display Derived
// 調用派生類的derivedFunction方法(需要類型轉換)
dynamic_cast<Derived*>(basePtr)->derivedFunction(); // 輸出: Derived Function
return 0;
}
使用虛函數實現運行時多態:
在基類中使用virtual關鍵字聲明的方法可以在派生類中被重寫,并且在運行時根據對象的實際類型調用相應的方法。
// Base.h
class Base {
public:
virtual void display() const {
std::cout << "Display Base" << std::endl;
}
};
// Derived.h
class Derived : public Base {
public:
void display() const override {
std::cout << "Display Derived" << std::endl;
}
};
在CentOS環境下,你可以使用g++編譯器來編譯和運行你的C++程序。
g++ -o polymorphism_example main.cpp Base.cpp Derived.cpp
./polymorphism_example
class Derived : public Base實現。希望這些步驟能幫助你在CentOS環境下實現C++的繼承和多態。如果有任何問題,請隨時提問!