2015-05-16 42 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,我同意你的意见。 –

相关问题