2017-05-23 15 views
-1

私は、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; 
}; 
+2

コピーを作成する必要はありませんが、ただやる 'temp-> S->のtoString()' ' –

+1

const'パラメータはちょうど関数はオブジェクトを変更しないことを示しています。あなたはそれを渡すために 'const'にキャストする必要はありません、ちょうど服従は十分でなければなりません。 – Donnie

答えて

1

const_cast削除しています const-nessなので、この場合は使用したくないでしょう。 Nodeさんsフィールド以来

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; 
    } 
} 
+0

説明していただきありがとうございます! –

+0

あなたは大歓迎です! –

関連する問題