【发布时间】:2023-03-07 15:33:01
【问题描述】:
我正在编写代码来处理“Foo”类型的对象。 foo 是一种容器,为了提供对其元素的高效和抽象访问,它提供了一个 Element 类型的嵌套类。一个Element 包裹了对象在容器中的位置。
现在,“Foo”可能有不同的实现,所以我正在编写一个抽象基类FooInterface 来为它们提供一个通用接口。问题是每个实现可能需要定义自己的Element 类型。例如,一个实现可以将其数据保存在一个向量中,这样它的Element 包装一个向量迭代器,而另一个实现包含一个列表,它的Element 包装一个列表迭代器。
我已经制定了一个使用 void 指针的解决方案。本质上,基类定义了一个包装了 void 指针的Element 类。 FooInterface 的不同实现可以将 void 指针转换为它们用来表示元素的任何类型。暂时忽略内存泄漏:
class FooInterface
{
public:
class Element {
void* payload;
public:
Element(void* payload) : payload(payload) {}
void* getPayload() const { return payload; }
};
virtual void say_element(Element) = 0;
virtual Element getElement() = 0;
};
class FooOne : public FooInterface
{
public:
virtual void say_element(Element element)
{
std::cout << "FooOne says: " <<
* (int *) element.getPayload() << "." << std::endl;
}
virtual Element getElement()
{
return Element(new int(42));
}
};
class FooTwo : public FooInterface
{
public:
virtual void say_element(Element element)
{
std::cout << "FooTwo says: " <<
* (std::string*) element.getPayload() << "." << std::endl;
}
virtual Element getElement()
{
return Element(new std::string("This is a test"));
}
};
void say(FooInterface& foo)
{
FooInterface::Element el = foo.getElement();
foo.say_element(el);
}
int main()
{
FooOne foo_one;
FooTwo foo_two;
say(foo_one);
say(foo_two);
return 0;
}
虽然这可行,但似乎必须有更好的方法。我的理解是,如果可能的话,应该避免使用 void 指针。那么,这是实现这一目标的最佳方式吗?
编辑:
我在这篇文章中描述我想要做的事情确实做得很差。不过,这些答案有助于让我思考,我设计了一个我认为不错的解决方案here。
【问题讨论】:
-
您没有描述您需要解决的问题。这个想法听起来很糟糕,但没有上下文就无法判断它是否有价值。
-
很明显,在这里使用
FooOne foo1; FooTwo foo2; foo2.say_element(foo1.getElement())将是一个巨大的错误。您是否有可能拥有FooThree,在可能且有时需要拥有foo3.say_element(foo2.getElement())的地方?或者强制各种元素类都具有不同的类型会更好吗? -
'我的理解是应该避免使用void指针'如果你有接口,一般不需要备份@ 987654334@指针?!?
标签: c++ inheritance interface