问题描述
为什么C ++中的类必须声明它们的私有函数?是否有实际的技术原因(在编译时它的作用是什么)还是仅仅是为了一致性?
如果你考虑它,这类似于在文件中声明一些函数 static
。它从外部不可见,但它对编译器本身很重要。编译器想知道函数的签名,然后才能使用它。这就是为什么你首先声明函数。 请记住,C ++编译器是一个遍,这意味着必须在使用之前声明所有内容。
从程序员的角度来看,声明私有函数仍然没有完全无用。想象2类,其中一个是朋友
的另一个。好友区类需要知道该类的私有如何,(这个讨论变得怪异)否则他们不能使用它。
至于为什么C ++是这样设计的,我首先说的是历史的原因:你不能在C中切分结构的事实,被C ++采用,所以你不能切分类(并且从C ++分支的其他语言也采用)。我也猜想它是关于简单性:想象一下,设计一个编译方法有多困难,你可以在不同的头文件之间拆分类,让你的源文件知道它,并阻止其他人添加东西到你的类。
最后一点是, private
函数可以影响vtable大小。也就是说,如果他们 virtual
。
1
Why do classes in C++ have to declare their private functions? Has it actual technical reasons (what is its role at compile time) or is it simply for consistency's sake?
If you think about it, this is similar to declaring some functions static
in a file. It's not visible from the outside, but it is important for the compiler itself. The compiler wants to know the signature of the function before it can use it. That's why you declare functions in the first place. Remember that C++ compilers are one pass, which means everything has to be declared before it is used.
From the programmer's point of view, declaring private functions is still not completely useless. Imagine 2 classes, one of which is the friend
of the other. The friendzoned class would need to know how the privates of that class look like, (This discussion is getting weird) otherwise they can't use it.
As to why exactly C++ was designed in this way, I would first say there is the historical reason: the fact that you can't slice a struct in C, was adopted by C++ so you can't slice a class (and adopted by other languages branched from C++, too). I'd also guess that it's about simplicity: Imagine how difficult it would be to devise a method of compilation in which you can split the class among different header files, let your source files know about it, and prevent others from adding stuff to your class.
A final note is that, private
functions can affect vtable size. That is, if they are virtual
.
这篇关于C ++:为什么必须声明私有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!