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