在C++中,多態性可以通過虛函數(virtual function)和純虛函數(pure virtual function)來實現接口統一。以下是實現接口統一的一些建議:
class Base {
public:
virtual void interfaceFunction() = 0; // 純虛函數
};
class Derived1 : public Base {
public:
void interfaceFunction() override {
// 實現具體功能
}
};
class Derived2 : public Base {
public:
void interfaceFunction() override {
// 實現具體功能
}
};
int main() {
Base* basePtr = new Derived1();
basePtr->interfaceFunction(); // 調用Derived1的接口函數
delete basePtr;
basePtr = new Derived2();
basePtr->interfaceFunction(); // 調用Derived2的接口函數
delete basePtr;
return 0;
}
class Abstract {
public:
virtual void interfaceFunction() = 0; // 純虛函數
virtual ~Abstract() {} // 虛析構函數,以確保正確的析構派生類對象
};
class Concrete1 : public Abstract {
public:
void interfaceFunction() override {
// 實現具體功能
}
};
class Concrete2 : public Abstract {
public:
void interfaceFunction() override {
// 實現具體功能
}
};
int main() {
Abstract* abstractPtr = new Concrete1();
abstractPtr->interfaceFunction(); // 調用Concrete1的接口函數
delete abstractPtr;
abstractPtr = new Concrete2();
abstractPtr->interfaceFunction(); // 調用Concrete2的接口函數
delete abstractPtr;
return 0;
}
通過這兩種方法,可以實現C++中的多態性,從而統一接口。