3

据我了解,C++ 类中的非静态数据成员被打包到 C 风格的结构中。为了简化讨论而忽略虚函数和继承,在这种方案中如何强制执行访问说明符?

说一堂课:

class Object
    {
public:
    int i1;
    int i2;
private:
    char i3;
    int i4;
    };

翻译为:

struct { 
  int i1;
  int i2;
  char i3;
  int i4;
}

c++如何保证私有成员i3andi4不能在类外访问但是i1andi2可以呢?

4

4 回答 4

5

C++ 有(一些)安全防护措施来防止墨菲,而不是马基雅维利。

这意味着在编译时const检查,volatile和访问限定符,但即使这样也可以绕过(使用各种技巧)。

所以... C++ 不需要实现保护方案。如果程序已编译,则认为它是正确的(使用那些限定符)并且将在没有运行时检查的情况下执行。

于 2012-06-11T07:00:07.420 回答
3

It doesn't. Go ahead, do a reinterpret_cast and manually index the pointer. This is for the same reason that both C and C++ allow for const to be cast away.

However, generally speaking, it's an idiotic idea to do so and C++ effectively enforces access modifiers by simply checking the modifier when you access in the normal way.

于 2012-06-11T06:49:29.637 回答
1

C++ 是一种静态类型语言。同样,C++ 中的许多概念也是静态检查的。具体来说,访问说明符在编译时进行检查。

该标准提供了一些关于类成员在内存中的布局方式的保证。最有用的是,在同一访问说明符部分中一起指定的成员将按指定的顺序可用。(例如,这个特性对于访问网络数据包非常有用。)

要回答您的问题,结构没有“翻译”(结构是退化的类,其中默认访问是公共的而不是私有的)。访问说明符在编译时强制执行。访问说明符没有运行时强制执行。

于 2012-06-15T16:04:24.063 回答
0

What's your source? I think it refers to how the objects are represented in memory, but it's the compiler, not the run-time, that deals with access specifiers.

In memory, a class might look the same as a struct, but to the compiler they do not.

Also, the two don't have to be equivalent even in memory (much like they are not equivalent for the compiler). The compiler can re-arrange the members, as long as it keeps those with no interleaving access specifiers grouped together. So, in memory,

class Object {  
public: 
   int i1; 
   int i2; 
private: 
   char i3; 
   int i4; 
};

could theoretically be represented as

struct {
   char i3;
   int i4;
   int i1;
   int i2;
}

Note that I'm only talking about the memory layout here. The actual struct equivalent of your class is:

struct Object {  
private:
public: 
   int i1; 
   int i2; 
private: 
   char i3; 
   int i4; 
};
于 2012-06-11T06:49:15.363 回答