不能分配抽象类型的对象
cannot allocate an object of abstract type
在下面的代码片段中,我在添加纯虚函数createImage时出现以下错误GUIFactory 类。
错误:无法分配抽象类型为"工厂"的对象
这里的工厂不是一个抽象类,所以理想情况下它应该是可实例化的。除此之外,如果删除此功能并且只添加了纯虚拟创建按钮,那么我没有收到此错误,这似乎是有效的行为。
法典:
#include <iostream>
#include<string.h>
using namespace std;
class Button {
public:
virtual void paint() = 0;
};
class Image {
public:
virtual void paint() = 0;
};
class OSXButton: public Button {
public:
void paint() {
std::cout << "OSX button n";
}
};
class WindowsButton: public Button {
public:
void paint() {
std::cout << "Windows button n";
}
};
class iPhoneButton: public Button {
public:
void paint() {
std::cout << "iPhone button n";
}
};
class OSXImage: public Image {
public:
void paint() {
std::cout << "OSX button n";
}
};
class WindowsImage: public Image {
public:
void paint() {
std::cout << "Windows button n";
}
};
class iPhoneImage: public Image {
public:
void paint() {
std::cout << "iPhone button n";
}
};
class GUIFactory {
public:
virtual Button *createButton(const char *) = 0;
virtual Image *createImage(const char *) = 0;//If this function is commented code works fine.
};
class Factory: public GUIFactory {
public:
Button *createButton(const char *type) {
if(strcmp(type,"Windows") == 0) {
return new WindowsButton;
}
else if(strcmp(type,"OSX") == 0) {
return new OSXButton;
}
else if(strcmp(type,"iPhone") == 0) {
return new iPhoneButton;
}
else
{
return NULL;
}
}
#if 0
Image *createImage(const char *type) {
if(strcmp(type,"Windows") == 0) {
return new WindowsImage;
}
else if(strcmp(type,"OSX") == 0) {
return new OSXImage;
}
else if(strcmp(type,"iPhone") == 0) {
return new iPhoneImage;
}
else
{
return NULL;
}
}
#endif
};
int main()
{
GUIFactory* guiFactory;
Button *btn;
Image *img;
guiFactory = new Factory;
btn = guiFactory->createButton("OSX");
if(btn!=NULL)
{
btn -> paint();
}
btn = guiFactory->createButton("Windows");
if(btn!=NULL)
{
btn -> paint();
}
btn = guiFactory->createButton("iPhone");
if(btn!=NULL)
{
btn-> paint();
}
#if 0
img = guiFactory->createImage("OSX");
if(img!=NULL)
{
img -> paint();
}
img = guiFactory->createImage("Windows");
if(img!=NULL)
{
img -> paint();
}
img = guiFactory->createImage("iPhone");
if(img!=NULL)
{
img -> paint();
}
//btn -> paint();
#endif
delete guiFactory;
// delete Button;
return 0;
}
删除#if 0
并围绕createImage
的定义#endif
。
它们的存在消除了定义,因此Factory
不会覆盖纯虚函数,因此仍然是抽象的。
相关文章:
- std::unordered_map 类型对象声明期间出现"field has incomplete type"错误
- C++ 多态模板类,模板类型对象的实例化
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- C++:初始化指向具有不同类型对象的指针数组
- 在类 C++ 中构造的模板类型对象
- 如何将颁发者名称设置为x509_req类型对象
- 将任何数据类型/对象作为参数传递以确定其大小
- 将引用类型对象的数组从C#封送到C++
- <T> 从类型对象创建类型<T1>对象的构造函数
- C++是否有现有的方法来检查对象是否是派生类型对象
- C 模板:创建与现有对象相同的类型对象
- 链接列表中的虚函数 - 多种返回类型(对象)
- 没有适当操作员()的类型对象的呼叫
- 制作垫子类型对象的数组.输出窗口显示同一帧
- 抽象类型对象的分配
- 在std::list中就地创建自定义类型对象
- 接受泛型列表类型对象的参数
- C++-将模板类型对象强制转换为特定的数据类型
- 试图在C++中打印存储在类型对象数组中的信息