在C ++ / QT中创建抽象类对象的QList? [英] Making a QList of an abstract class objects in C++/QT?
问题描述
尽管这里的其他问题/答案已经无数次地帮助了我,但这是我的第一个问题,所以请不要对我太苛刻! :)
although I've been helped countless times by other questions/answers here, this is my first question here, so don't be too harsh on me! :)
我一直在学习QT / C ++,并假设我有这样的东西:
I've been learning QT/C++ and let's assume I have something like this:
class AbstractMasterClass{
public:
virtual void foo(void) = 0; //Pure virtual method
}
该类将有很多子类,每个子类实现自己的foo()方法。
问题是:如何创建一个将用AbstractMasterClass的子类填充的QList?
This class will have plenty subclasses, each one of them implementing their own foo() method. And the question is: How can I create a QList which I'll populate with AbstractMasterClass's subclasses?
目标是能够遍历列表为每个元素调用foo()方法,即使用主类,就像我对Java接口所做的一样。
经过几次尝试,我最终遇到了几个编译时错误,这些错误表明我们在创建QList时无法(显然)分配抽象类的对象。
The objective is to be able to iterate through the list calling the foo() method for every element, i.e. use the master class the same way I would do to a Java interface. The few tries I ended up getting several compile time errors saying that we can't allocate an object of an abstract class (obviously) while creating the QList.
那么我该怎么做,还是有更好的方法在C ++ / QT中制作类似Java的接口?
So how can I do it or is there a better way to make a java like interface in C++/QT?
在此先感谢大家的回答或指点。
Thank you all in advance for your time answering or pointing me in the right direction!
推荐答案
这是一个通用的C ++问题,而不是Qt问题。在这种情况下,您可能想使用多态性。创建类型为AbstractMasterClass的指针,并使其指向您的派生类之一,然后将指针存储在列表中。我在下面的示例中使用了QSharedPtr,以避免您需要手动删除内存。
This is a general C++ question more than a Qt issue. You would want to use polymorphism in this case. Create a pointer of type AbstractMasterClass and make it point to one of your derived classes, then you store the pointers in your list. I used QSharedPtr in the example below to avoid you needing to do any manual deletion of memory.
class AbstractMasterClass {
public:
virtual ~AbstractMasterClass(){}; // virtual destructor so derived classes can clean up
virtual void foo() = 0;
};
class DerivedA : public AbstractMasterClass {
public:
void foo() { cout << "A\n"; }
};
class DerivedB : public AbstractMasterClass {
public:
void foo() { cout << "B\n"; }
};
int main() {
QList<QSharedPtr<AbstractMasterClass>> myList;
QSharedPtr<AbstractMasterClass> a(new DerivedA());
QSharedPtr<AbstractMasterClass> b(new DerivedB());
myList.push_back(a);
myList.push_back(b);
for (auto &it : myList) {
it->foo();
}
return 0;
}
这篇关于在C ++ / QT中创建抽象类对象的QList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!