在C++中,我们可以使用虚函数和多态性来有效地将基类进行"upcast"或者克隆为扩展类。基类中的虚函数可以在派生类中被重写,从而实现对基类的扩展。
以下是一个示例代码,演示了如何将基类"upcast"为扩展类:
#include
class Base {
public:
virtual void print() {
std::cout << "This is the Base class." << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "This is the Derived class." << std::endl;
}
void newFunction() {
std::cout << "This is a new function in the Derived class." << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
basePtr->print(); // 输出 "This is the Derived class."
Derived* derivedPtr = dynamic_cast(basePtr);
derivedPtr->newFunction(); // 输出 "This is a new function in the Derived class."
delete basePtr;
return 0;
}
在上面的代码中,基类Base
有一个虚函数print()
,派生类Derived
重写了该函数,并添加了一个新的函数newFunction()
。
在main()
函数中,我们首先通过使用基类指针指向派生类对象,实现了基类的"upcast"。然后,我们使用dynamic_cast
将基类指针转换为派生类指针,以便可以调用派生类中的新函数newFunction()
。
通过使用虚函数和多态性的机制,我们可以有效地将基类进行"upcast"或者克隆为扩展类。
上一篇:不知道结构,将字符串分割成结构体