【发布时间】: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->s->toString() -
一个
const参数只是表示函数不会修改对象。您不必为了传递它而强制转换为const,只要尊重就足够了。
标签: c++ pointers linked-list constants