如何将const Class*转换为Class* ?

How would I convert a const Class* to a Class*?

本文关键字:Class 转换 const      更新时间:2023-10-16

我试图插入一些东西到链表,但编译器告诉我,我不能从const Student*转换到Student*。每个节点包含一个Student *stud和一个Node *next。这是我目前所写的函数:

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)函数的参数?

如何将const Class*转换为Class*?

选项1:

复制一份

p->stud = new Student(student);

选项2:

使用const_cast .

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

仅在仔细管理内存时使用此选项