私は、Studentクラスから以前に作成されたtoString関数を実装して、StudentポインタのリンクリストのtoString関数を記述しようとしています。オブジェクトへのポインタを定数逆参照オブジェクトにするにはどうすればよいですか?
私の問題は、リンクされたリストをトラバースすると、StudentクラスからtoStringを呼び出すために各Studentオブジェクトを作成する際に問題が発生していることです。
私は、新しい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'にキャストする必要はありません、ちょうど服従は十分でなければなりません。 – Donnie