我刚刚浏览了一些 C++ 代码。
我在哪里遇到了 reinterpret_cast
运算符的概念。
编辑 1:
我知道不建议访问类的私有(private)成员。 但在某些情况下,我们应该继续访问它们。 我刚才提出这个问题是为了弄清楚我的概念。
在我提到的例子中,类的私有(private)成员通过简单地创建一个具有相同变量的结构来访问,然后通过实现修改
reinterpret_cast
运算符。
我已经理解了reinterpret_cast
运算符的用法,因为我知道它的是什么,但是我不明白如何一个结构可以用于修改私有(private)类成员的值。
以下是我引用的源代码:
类:
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;
};
用于访问和修改私有(private)类成员的结构:
struct _Student
{
void* vptr;
int id;
float score;
};
_Student* bs3 = reinterpret_cast<_Student*>(bs2);
bs3->id = 5;
谢谢。如果我错了/我不能以适当的方式提出我的问题,请纠正我。
最佳答案
$5.2.10/2 - "An expression of integral, enumeration, pointer, or pointer-to-member type can be explicitly converted to its own type; such a cast yields the value of its operand."
这意味着指针 'bs2' 和 'bs3' 指向相同的位置
$9.2/16 - "Two standard-layout struct (Clause 9) types are layout-compatible if they have the same number of non-static data members and corresponding non-static data members (in declaration order) have layout-compatible types (3.9)."
这意味着您的类和结构是布局兼容的。
$9/6-
A standard-layout class is a class that:
— has no non-static data members of type non-standard-layout class (or array of such types) or reference,
— has no virtual functions (10.3) and no virtual base classes (10.1),
— has the same access control (Clause 11) for all non-static data members,
— has no non-standard-layout base classes,
— either has no non-static data members in the most-derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and
— has no base classes of the same type as the first non-static data member.108
因为你的类有一个虚拟析构函数,你的类和结构不是标准的布局类。
但是您已经添加了一个“void *”数据成员来可能处理“vptr”(因此可能会根据您的特定编译器实现模仿布局兼容性)
在这种情况下,reinterpret_cast 用于将类指针 (bs2) 解释为结构指针 (bs3)。默认情况下,结构成员是公共(public)的。由于reinterpret cast的返回值指向类成员所在的同一 block 内存(引用上面的引述),所以可以修改struct成员(与原来的类成员相同)。
这是作弊。这是非常气馁的。!这很可能会导致未定义的行为
关于c++ - 在创建结构时修改类私有(private)成员 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820363/