C ++:为什么必须声明私有函数? [英] C++: Why must private functions be declared?

查看:341
本文介绍了C ++:为什么必须声明私有函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么C ++中的类必须声明它们的私有函数?是否有实际的技术原因(在编译时它的作用是什么)还是仅仅是为了一致性?

解决方案


我问为什么必须声明私有函数,因为它们不会为其他翻译单元添加任何东西(对象大小和vtable条目都不知道)


如果你考虑它,这类似于在文件中声明一些函数 static 。它从外部不可见,但它对编译器本身很重要。编译器想知道函数的签名,然后才能使用它。这就是为什么你首先声明函数。 请记住,C ++编译器是一个遍,这意味着必须在使用之前声明所有内容。 1

从程序员的角度来看,声明私有函数仍然没有完全无用。想象2类,其中一个是朋友的另一个。好友区类 2 需要知道该类的私有如何,(这个讨论变得怪异)否则他们不能使用它。



至于为什么C ++是这样设计的,我首先说的是历史的原因:你不能在C中切分结构的事实,被C ++采用,所以你不能切分类(并且从C ++分支的其他语言也采用)。我也猜想它是关于简单性:想象一下,设计一个编译方法有多困难,你可以在不同的头文件之间拆分类,让你的源文件知道它,并阻止其他人添加东西到你的类。



最后一点是, private 函数可以影响vtable大小。也就是说,如果他们 virtual






1 实际上并不完全。如果在类中有内联函数,它们可以引用稍后在同一类中定义的函数。但是可能这个想法是从单个传递开始的,这个异常后来添加到它。



2


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?

解决方案

I asked why private functions had to be declared at all, as they don't add anything (neither object size nor vtable entry) for other translation units to know

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

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


1 Actually not entirely. If you have inline functions in the class, they can refer to functions later defined in the same class. But probably the idea started from single pass and this exception later added to it.

2 It's inlined member functions in particular.

这篇关于C ++:为什么必须声明私有函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆