2015-05-16 75 views
-1

我想插入一些東西到鏈接列表中,但編譯器告訴我,我無法從const Student*轉換爲Student*。 每個節點包含一個Student *stud和一個Node *next。這是我迄今爲止功能的書面:如何將const Class *轉換爲Class *?

void LinkedList::putAtTail(const Student &student){ 
    Node *p = new Node(); 
    p->stud = &student; //this is where I have trouble 
    p->next - NULL; 

    //then insert `p` into the Linked List 
} 

編譯器不希望編譯這個,給我error: invalid conversion from ‘const Student*’ to ‘Student*’

我該如何解決這個問題,而不改變我的putAtTail(const Student &student)函數的參數?

+1

請顯示Node的聲明。 –

+0

因爲'&student'在這方面與'student'完全不同。 –

+0

你可能想要添加一個參數的副本。 –

回答

0

我該如何將const Class *轉換爲Class *?

選項1:

製作副本。

p->stud = new Student(student); 

選項2:

使用const_cast

p->stud = const_cast<Student*>(&student); 

只有當您仔細管理內存時才使用此選項。

+0

該副本幾乎可以肯定是什麼意圖。學生對象甚至可能在只讀存儲器中,以便稍後進行寫入訪問(因爲const信息已被丟棄)會立即使程序崩潰。 –

+0

@PeterSchneider,我同意你的意見。 –

相關問題