如何将指向对象的指针转到常量取消引用的对象
How can I turn a pointer to an object to a constant dereferenced object?
我正在尝试为学生指针的链表编写一个toString函数,实现以前从学生类创建的toString函数。
我的问题是,当我遍历链表时,我在创建每个 Student 对象以便从 Student 类调用 toString 时遇到问题。
我认为这与在构造新的 Student 对象时需要一个 const 和 Student 参数这一事实有关,但我不知道如何将每个 temp-> 更改为常量 &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;
}
}
这是我的学生:
#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
};
这是学生卷。
#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;
};
const_cast
删除了常量,因此在这种情况下您不想使用它。
由于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;
}
}
相关文章:
- 代理对象的常量正确性
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 如何使用数据对象上的常量指针初始化类
- 为什么C++在将一个对象复制到另一个对象时需要对这两个对象进行低级常量限定
- 为什么当我们有常量引用时创建临时对象?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- C++,如何使用常量对象和非常量对象进行比较?
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- C++将常量字符* 指针数组传递给对象
- C++ 对非常量对象的常量引用和对非常量对象的非常量引用之间的区别
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- 当类具有常量时,将对象插入到向量中
- 算法不适用于非常量对象的const_iterator
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 为什么MSVC14允许声明指向动态未初始化常量对象的指针
- 可作为常量调用的比较对象
- C++中的常量对象或私有/常量数据成员(变量)?
- 将值从指针复制到常量对象参数
- 如何正确组合可变对象常量