成员函数和复制构造函数
您必须显式列出要在复制构造函数中复制的所有成员,这意味着您可以设置复制构造函数来复制对象的缩减版本。
但是成员函数复制是如何工作的呢?所有成员函数都自动包含在内吗?这是因为对象实际上只是成员,而函数只是声明如何使用类?这是否意味着理论上您可以使用复制构造函数创建缩减对象,然后调用 getter 来获取副本中不存在的成员?
You have to explicitly list all of the members that you want copied in a copy constructor, this means that you could set up a copy constructor to copy cut down versions of your object.
but how does the member function copying work? are all member functions automatically included? Is this because an object is really just the members and the functions just declare how a class can be used? Does this mean you could in theory create cut down objects with a copy constructor and then, for example, call a getter to get a member that doesn't exist in your copy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
成员函数不存储在类实例中。它们只是常规函数。但是可以存储 vtable 指针。它用于动态分配虚拟成员函数。
正常的成员函数调用是在编译时确定的。
(顺便说一句,有些语言确实为每个实例存储方法的副本,尽管 C++ 不是其中之一)
Member functions are not stored in class instances. They're just regular functions. A vtable pointer can be stored however. It is used for dynamic dispatch of virtual member functions.
Normal member function calls are determined at compile time.
(as a side-note, there are some languages that do store copies of methods per-instance, although C++ isn't one of them)
函数的每个实例没有单独的实例; (非静态)成员函数的特征不是它将为每个实例实例化,而是必须在实例上调用它,并且将隐式接收指向该实例的指针。没有函数的复制。 (事实上,函数(成员函数或其他函数)无法复制。)
Functions don't have a separate instance for each instance; the characteristic of a (non-static) member function isn't that it will be instantiated for each instance, but that it must be called on an instance, and will implicitly receive a pointer to the instance. There's no copying of functions. (In fact, functions—member or otherwise—can't be copied.)
对于 C++ 中的类/对象是什么,可能存在误解。在某些语言中(例如Python),对象可以改变(新变量/函数);在C++中,对象是静态的,正如在类中指定的那样,因此不能有对象的缩小版本。
默认的复制构造函数已经执行成员到成员的复制。如果这还不够(浅复制<->深复制),您必须提供您自己的复制构造函数版本,您必须在其中完成所有复制。未能复制成员将使复制的版本保留未定义或默认成员。最好通过避免动态内存等来避免创建自己的复制构造函数。
There is probably a misunderstanding about what classes/objects are in C++. In some languges (e.g. python), objects can change (new variables/functions); in C++, objects are static, as specified in the class, so there can not be shrinked down version of your object.
The default copy constructor already does a member to member copy. If this is not enough (shallow copy <-> deep copy), you have to provide your own version of the copy constructor in which you have to do all the copying. Failing to copy a member will leave the copied version with an undefined or default member. It is best to avoid having to make your own copy constructor by avoiding dynamic memory and the likes.