【问题标题】:QList pointer function to abstract class指向抽象类的 QList 指针函数
【发布时间】:2013-09-20 06:44:57
【问题描述】:

我觉得问这个问题很愚蠢,因为它看起来很简单,但我不知道该怎么做,而且我在互联网上的任何地方都找不到。我正在尝试创建一个将 QList 返回到标准输出的函数,指向抽象类的指针让我感到困惑。 AbstractStudent 类生成另一个Student 类的实例。这是函数:

QList<AbstractStudent*>* StudentList::returnList() const{


}

【问题讨论】:

  • 那么问题/疑问是什么?现在,您正在返回一个指向包含基类指针的QList 的指针。我不明白您为什么需要将 指针 返回到 QList,但它仍然有效。
  • 你想将 QList 的内容打印到控制台吗?
  • 将列表发送到标准输出,以便在 QTextEdit 中打印

标签: c++ qt qlist


【解决方案1】:

存储抽象类指针的列表将能够存储指向该抽象类的任何子类的指针。

想一想:

AbstractStudent.h:

class AbstractStudent 
{
    // ...
};

学生.h:

class Student : public AbstractStudent
{
    // ...
};

任何其他类 .cpp:

QList< AbstractStudent* > studentList;

// Each of the following works:
AbstractStudent* student1 = new Student( /* ... */ );
studentList.append( student1 );

Student* student2 = new Student( /* ... */ );
studentList.append( student2 );

Student* student3 = new Student( /* ... */ );
AbstractStudent* student3_1 = student3;
studentList.append( student3 );

但是,我对您的最后一句话感到有些困惑,声称 AbstractStudent 生成 Student 对象。我本来希望 Student 继承 AbstractStudent 而其他一些类生成 Student 对象,就像在我的示例中一样。

【讨论】:

  • AbstractStudent 是具体 Student 类的基类。 StudentList 被实现为一个指向 AbstractStudent 实例的指针列表——然后该列表将包含指向具体学生实例实例的指针。 StudentList 是用 Singleton 设计模式实现的。 (这就像编程的初始阶段:D)。谢谢帮助
  • 好的。一开始听起来像 AbstractStudent 的代码中有new Student(),所以我很困惑。 ;-) 不过,在你对单例太感兴趣之前,我建议阅读:stackoverflow.com/questions/137975/…misko.hevery.com/2008/08/17/singletons-are-pathological-liars
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 2015-12-28
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多