gpt4 book ai didi

c++ - 带有参数列表的父类(super class)方法 与专用列表一起使用

转载 作者:行者123 更新时间:2023-11-28 04:27:55 25 4
gpt4 key购买 nike

我是 C++ 的新手,我正在尝试开发一个 2D 模拟,其中每个表示的元素都是 Point 的子类。我有几个每个子类的列表(listA,listB ...)。

我正在尝试实现一个找到离当前点最近的点的函数,例如,哪个 B 实例最接近当前 A 实例。将此函数放在 Point 类中对我来说很有意义,因为每个子类都可以使用它,但是由于我的程序使用专门项目的列表( std::list<A> 而不是 std::list<Point> ),我收到以下代码的错误:

class Point 
{
Point* findClosest(std::list<Point*>&);
};

class A : public Point
{
void update(std::list<B*>&);
};

class B : public Point
{
};

void A::update(std::list<B*>& blist)
{
B* closest = this->findClosest(blist); //bug
// do something...
}

错误信息:

error: no matching function for call to ‘A::findClosest(std::__cxx11::list<A*>&)’

note: no known conversion for argument 1 from ‘std::__cxx11::list<A*>’ to ‘std::__cxx11::list<Point*, std::allocator<Point*> >&’

如果我使用 Point 列表而不是专用元素列表,它会起作用,但每次我需要使用特定于该类的方法(如 update()对于 A 类)。

有什么方法可以将我的 A 列表解释为点列表?

感谢帮助!

最佳答案

你不能这样做因为list<B*>不继承自 list<Point*> .

在您的情况下,您可能不得不仅使用 list<Point*> 来工作并实例化每个 Point作为 AB : 让 Point 的虚函数为你做分离。虽然,一般来说,由于各种原因我不推荐这样的设计(由于使用过多的分配和释放会导致内存碎片问题,因此运行时间会很慢;也会有太多的虚函数调用;不要忘记内存泄漏,以防您忘记释放)

如果你真的想通过list<B*>对于任意类,那么您将不得不使用模板,但我认为这些对您来说还为时过早。

class Point 
{
template<class T>
Point* findClosest(std::list<T*>&)
{
// write implementation here in .h; not in .cpp
}
};

关于c++ - 带有参数列表的父类(super class)方法 <superclass> 与专用列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53824429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com