问题描述
考虑代码
A级{
私人:
int a;
};
int main(无效){
A x;
int * ptr =(int *)& x ;
* x = 10;
返回0;
}
我明白我不能改变类的私有属性,
但标准对上面的代码有什么看法?
Consider the code
class A {
private:
int a;
};
int main(void) {
A x;
int* ptr = (int*)&x;
*x = 10;
return 0;
}
I understand that I can not change the private attributes of a class,
but what does standard have to say about the code above?
推荐答案
它的行为未定义。它可能会工作......它可能不会......它
可能会结束你所知道的世界......未定义。
That its behavior is undefined. It might work...it might not...it
might end the world as you know it...undefined.
-Tomás
-Tomás
哦,我在这里错过了什么。 * ptr = 10;本来是未定义的。 * x
= 10无法编译,因为A没有操作员*。
BTW,(int *)& x是完全合法。它是一个C风格的演员阵容,并且与所有C风格的演员阵容一样,它可以做出意想不到的事情。这个
解析的是reinterpret_cast< int *>(& x)。这当然是合法的
但是结果不明确。 static_cast是非法的并且使用
C ++转换机制会警告你关于演员的未定义的
性质......这就是为什么C-Style演员阵容很糟糕。
Oh, I missed something here. *ptr = 10; would have been undefined. *x
= 10 doesn''t compile as A doesn''t have an operator*.
BTW, (int*)&x is totally legal. It is a C-style cast and as is the
case with all C-style casts it can do things unexpectedly. What this
resolves to is a reinterpret_cast<int*>(&x). This is of course legal
but has undefined results. A static_cast would be illegal and using
the C++ casting mechanism would have warned you about the undefined
nature of the cast...this is why C-Style casts are bad.
这篇关于通过类型转换访问类的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!