C++ 如何将指向对象的指针转换为常量解引用对象?

C++ 如何将指向对象的指针转换为常量解引用对象?,c++,pointers,linked-list,constants,C++,Pointers,Linked List,Constants,我试图为学生指针的链接列表编写一个toString函数,实现一个以前从学生类创建的toString函数 我的问题是,当我遍历链表时,为了从Student类调用toString,我在创建每个Student对象时遇到了问题 我认为这与构造新的Student对象时需要const&Student参数有关,但我不知道如何将每个temp->s更改为constant&Stud。我可以使用const_cast吗,如下图所示 这就是我到目前为止所做的: std::string StudentRoll::toStr

我试图为学生指针的链接列表编写一个toString函数,实现一个以前从学生类创建的toString函数

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

我认为这与构造新的Student对象时需要const&Student参数有关,但我不知道如何将每个temp->s更改为constant&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;
  }
}
std::string StudentRoll::toString()常量{
节点*温度=头部;
while(temp!=NULL){//我的尝试
学生新闻学生(const_cast(temp->s));
*(newStudent).toString();//学生类中的toString函数
温度=温度->下一步;
}
}
这是我的学生。h:

#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
};
#包括
班级学生{
公众:
学生(常量字符*常量名称,int perm);
int getPerm()常量;
常量字符*常量getName()常量;
void setPerm(const int perm);
void setName(常量字符*常量名称);
学生(const Student&orig);
~Student();
学生和操作员=(常量学生和右侧);
std::string toString()常量;
私人:
int-perm;
char*name;//在堆上分配
};
这是StudentRoll.h

#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;
};
#包括
#包括“student.h”
班级学生名册{
公众:
学生卷();
无效插入附件(const Student&s);
std::string toString()常量;
学生名册(const StudentRoll&orig);
~StudentRoll();
StudentRoll和operator=(const StudentRoll和right);
私人:
结构节点{
学生证;
节点*下一步;
};
节点*头;
节点*尾部;
};

常量转换将删除常量,因此您不希望在这种情况下使用它

由于
节点
s
字段是一个
Student*
,您只需取消引用它(
*
操作符)即可提取
Student
对象。当传递给
Student
的构造函数时,
const&
是隐式的

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


无需复制,只需执行
temp->s->toString()
a
const
参数指示函数不会修改对象。您不必通过强制转换到
const
来传递它,只要尊重就足够了。感谢您的澄清!
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;
    }
}