gpt4 book ai didi

c++ - 更改类的私有(private)成员

转载 作者:行者123 更新时间:2023-11-30 01:08:29 26 4
gpt4 key购买 nike

获取和修改私有(private)类成员的值:

#include <stdio.h>

class hack_Me
{
private:
size_t age;
public:
size_t getAge() const
{
return this->age;
}

explicit hack_Me(size_t age):age(age) { }

};

void change_age(hack_Me* h)
{
*((int*)h) = 100;
}

int main(int argc, char* argv[])
{
hack_Me h(12);
printf("%d \n", h.getAge());
change_age(&h);
printf("%d \n", h.getAge());

getchar();
return 0;
}

它在 12 之后打印 100。

它适用于 MSVC 14。

此行为是否未定义和/或依赖于编译器?

更新:StackOverflow 会为您提供否决票积分吗?

最佳答案

Is this behavior undefined and/or compiler dependent?

使用 int* 访问 size_t 类型的变量是不好的,无论该变量是在类内部还是它本身。

如果你使用

*(reinterpret_cast<size_t*>(h)) = 100;

这不是未定义的行为,也不依赖于编译器。我怀疑,如果您使用:

*((size_t*)h) = 100;

您的类(class)符合标准布局结构的要求。

来自 C++11 标准:

9 Classes

...

7 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.

8 A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

对于standard-layout struct,指向对象的指针可以别名为指向第一个成员变量的指针。

来自 C++11 标准:

9.2 Class members

...

20 A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ]

关于c++ - 更改类的私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42501659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com