5

我了解典型的访问说明符是什么,以及它们的含义。'public' 成员可以在任何地方访问,'private' 成员只能由同一个班级和朋友访问,等等。

我想知道的是,如果有的话,这相当于较低级别的术语。它们之间的任何编译后功能差异是否超出了它们所使用的语言(在这种情况下为 c++)所施加的高级限制(什么可以访问什么)。

另一种说法 - 如果这是一个完美的世界,程序员总是做出很好的选择(比如不访问以后可能会更改的成员,并且只使用在实现之间应该保持不变的定义明确的成员),他们是否有任何理由使用这些事物?

4

5 回答 5

10

访问说明符仅用于编译目的。可执行文件的任何部分都可以访问程序分配中的任何内存;运行时没有公共/私有概念

于 2010-05-03T16:57:16.800 回答
2

迈克尔的回答是正确的。访问说明符不直接影响生成的代码。

但是,访问说明符可以解决不明确的标识符/重载错误,否则会阻止编译。

class A {
private:
    int x;
};

class B {
protected:
    int x;
};

class C : public A, public B {
public:
    int &get_x() { return x; } // only B::x is accessible, no error.
};

因此,它们肯定比限制程序员具有更高的目的。

于 2010-05-03T19:37:22.903 回答
1

Post-compilation, you are left with machine code (assembly) which has no notion of "public" or "private" (or of classes, members, etc). Everything is simply a memory address (whether it's code or data), and can be accessed just like any other memory address. The whole public\private distinction (as well as almost every other construct available in a high-level language) is purely for the benefit of the programmer, allowing the compiler to enforce a set of rules that are intended to make the intent of the code clearer and to help avoid potential bugs. Once compiled, your code doesn't know what language it was originally written in, much less what type of access specifiers were used.

That being said, it would be possible to rig a compiler so that it modifies the code whenever a private class member function is called in order to detect when the function is called inappropriately (add an extra parameter and set it to some expected value when the function is called from within the class; calling the function from outside of the class would provide the wrong value). The problem with this approach is what do you do now? Lock up? Do nothing and return invalid data? These types of problems are (relatively) easily detectable and correctable at compile time, so it is rare to see this sort of thing enforced at run time (outside of debugging or code profiling tools).

于 2010-05-03T17:10:49.190 回答
1

您的问题的答案可能因编译器而异,但通常不会有任何区别。可以设想一种环境,其中编译的代码对于这些不同的可访问性可能具有不同的特征,但我不知道存在任何这种情况。

于 2010-05-03T16:59:15.390 回答
1

只有掌握了正确的信息,程序员才能做出正确的选择。访问修饰符是一种向程序员发出信号表明某些事情不应该被触及的方式,并且它具有强制执行正确行为的附带好处。

没有运行时影响。您可以使用正确的访问修饰符编写程序,使用 , 构建它,c++ -Dprotected=public -Dprivate=public file.cc它应该构建和生成几乎完全相同的代码(有一些假设性的警告,例如类的数据布局)。

于 2010-05-03T17:02:00.157 回答