在C++中,可以使用抽象基类和纯虚函数来实现不指定声明派生类的对象的解决方法。下面是一个示例代码:
#include
// 抽象基类
class Base {
public:
// 纯虚函数,没有实现
virtual void print() = 0;
};
// 派生类1
class Derived1 : public Base {
public:
void print() override {
std::cout << "Derived1" << std::endl;
}
};
// 派生类2
class Derived2 : public Base {
public:
void print() override {
std::cout << "Derived2" << std::endl;
}
};
int main() {
// 创建抽象基类的指针
Base* obj = nullptr;
// 根据需要创建不同的派生类对象
int choice;
std::cout << "请选择派生类:1 - Derived1,2 - Derived2" << std::endl;
std::cin >> choice;
if (choice == 1) {
obj = new Derived1();
} else if (choice == 2) {
obj = new Derived2();
}
// 调用抽象基类的纯虚函数
obj->print();
// 释放内存
delete obj;
return 0;
}
在上述代码中,抽象基类 Base
包含一个纯虚函数 print()
,没有实现。派生类 Derived1
和 Derived2
分别重写了基类的纯虚函数。在 main()
函数中,我们通过基类指针 Base* obj
来接收不同派生类的对象。根据用户的选择,我们可以创建不同的派生类对象,并调用基类的纯虚函数 print()
来输出相应的信息。最后,记得释放内存,避免内存泄漏。