我只是在浏览一些 C++ 代码。我在哪里遇到了reinterpret_cast
运营商的概念。
编辑 1:
我知道不建议访问类的私有成员。 但在某些情况下,我们应该继续访问它们。 我刚刚提出这个问题是为了弄清楚我的概念。
在我提到的示例中,通过简单地创建具有相同变量的结构来访问 Class 的私有成员,然后通过实现
reinterpret_cast
运算符进行修改。
我已经了解reinterpret_cast
运算符的用法,因为我知道它的作用,但我不明白如何使用结构来修改私有类成员的值。
以下是我提到的源代码:
班级:
class Student
{
public:
explicit Student(float percent) // Cannot be used for conversion
{
static int nid;
id = ++nid;
score = percent;
}
int Id() const
{
return id;
}
float GetScore() const
{
return score;
}
void SetScore(float value)
{
score = value;
}
virtual ~Student(){}
private:
int id;
float score;
};
用于访问和修改私有类成员的结构:
struct _Student
{
void* vptr;
int id;
float score;
};
_Student* bs3 = reinterpret_cast<_Student*>(bs2);
bs3->id = 5;
谢谢。如果我错了/我无法以适当的方式提出我的问题,请纠正我。