【问题标题】:C++ Pointer class in place of DATA TYPEC++ 指针类代替 DATA TYPE
【发布时间】:2021-11-29 12:40:07
【问题描述】:
class Student 
{ 
 public: //add any needed functions yourself 
 private: 
 string name; 
 int rollnumber; 
}

class University 
{ 
 public: 
// constructor 
 private: 
 int numberOfStudents; 
 SList<Student*> *list; // list is developed by me as a linked list but what is this Student* here, instead of just Student???
}

我见过SList&lt;Student&gt; *list 之类的东西,所以我可以通过说list = new SList&lt;Student&gt;; 在构造函数中创建一个新列表

但是在这里,由于Student*,它不起作用。我应该怎么做,声明它的语法是什么?

【问题讨论】:

  • 要创建一个(指向)SList&lt;Student*&gt; 的指针,您需要新建一个 SList&lt;Student*&gt;,而不是 SList&lt;Student&gt;
  • 几乎不应该创建容器指针(如向量或列表)。你可能应该有一个 objects 列表而不是指针。

标签: c++ pointers abstraction


【解决方案1】:

正如SList* 是指向SList 的指针一样,Student* 是指向Student 的指针。如果你想要 newSListStudent* 指针,它看起来像这样:

SList<Student*> *list;
...
list = new SList<Student*>;
...
delete list;

因此,您可能还需要 newdelete 要存储在列表中的每个 Student

SList<Student*> *list;
...
list = new SList<Student*>;
...
list->Add(new Student);
...
for (each student in the list)
    delete student;
delete list;

在现代 C++ 中,如果您需要在动态存储中使用指向对象的指针,则应尽量避免手动使用 newdelete。改用智能指针,例如 std:unique_ptr/std::make_unique()std::shared_ptr/std::make_shared()

std::unique_ptr<SList<std::unique_ptr<Student>> list;
...
list = std::make_unique<SList<std::unique_ptr<Student>>>();
...
list->Add(std::make_unique<Student>());
...
// no need for delete...

当然,如果可以避免使用动态存储,您应该根本不使用它。

SList<Student> list; // no need for new...
...
list->Add(Studen()); // no need for new...
...
// no need for delete...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2021-04-08
    • 2015-08-25
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多