【问题标题】:How can I turn a pointer to an object to a constant dereferenced object?如何将指向对象的指针转换为常量取消引用的对象?
【发布时间】:2017-05-23 01:19:49
【问题描述】:

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

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

我认为这与构造新 Student 对象时需要一个 const &Student 参数有关,但我不知道如何将每个 temp->s 更改为常量 &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;
  }
}

这是我的 Student.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
};

这是 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;
};

【问题讨论】:

  • 不需要复制,直接做temp-&gt;s-&gt;toString()
  • 一个const参数只是表示函数不会修改对象。您不必为了传递它而强制转换为const,只要尊重就足够了。

标签: c++ pointers linked-list constants


【解决方案1】:

const_cast 删除 const-ness,所以在这种情况下你不想使用它。

由于Nodes 字段是Student*,您只需取消引用它(* 运算符)即可提取Student 对象。当传递给Student 的构造函数时,const &amp; 是隐式的。

请尝试以下操作,了解您需要从 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;
    }
}

【讨论】:

  • 感谢您的澄清!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2016-07-18
  • 1970-01-01
  • 2021-06-19
  • 2021-07-22
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多