如何将指向对象的指针转到常量取消引用的对象

How can I turn a pointer to an object to a constant dereferenced object?

本文关键字:对象 常量 取消 引用 指针      更新时间:2023-10-16

我正在尝试为学生指针的链表编写一个toString函数,实现以前从学生类创建的toString函数。

我的问题是,当我遍历链表时,我在创建每个 Student 对象以便从 Student 类调用 toString 时遇到问题。

我认为这与在构造新的 Student 对象时需要一个 const 和 Student 参数这一事实有关,但我不知道如何将每个 temp-> 更改为常量 &Stud。我可以使用const_cast,如下所示吗?

这是我到目前为止所拥有的:

std::string StudentRoll::toString() const {
  Node* temp = head;
  while(temp != NULL){ //my attempt
        Student newStudent(const_cast <Student*> (temp->s));
        *(newStudent).toString(); //toString function from Student class            
        temp = temp->next;
  }
}

这是我的学生:

#include <string>
class Student {
 public:
  Student(const char * const name, int perm);
  int getPerm() const;
  const char * const getName() const;
  void setPerm(const int perm);
  void setName(const char * const name);
  Student(const Student &orig);
  ~Student();
  Student & operator=(const Student &right);
  std::string toString() const;
 private:
  int perm;
  char *name; // allocated on heap
};

这是学生卷。

#include <string>
#include "student.h"
class StudentRoll {
 public:
  StudentRoll();
  void insertAtTail(const Student &s);
  std::string toString() const;
  StudentRoll(const StudentRoll &orig);
  ~StudentRoll();
  StudentRoll & operator=(const StudentRoll &right);
 private:
  struct Node {
    Student *s;
    Node *next;
  };
  Node *head;
  Node *tail;
};

const_cast删除了常量,因此在这种情况下您不想使用它。

由于Nodes字段是一个Student*,你只需取消引用它(*运算符(来提取一个Student对象。 当传递给构造函数进行Student时,const &是隐式的。

请尝试以下操作,了解您需要从 StudentRoll::toString() 返回值。

std::string StudentRoll::toString() const {
    Node* temp = head;
    while(temp != NULL){ //my attempt 
        Student newStudent(*(temp->s));
        newStudent.toString(); //toString function from Student class            
        temp = temp->next;
    }
}