在C ++中使用构造函数 [英] Use of constructor in C++

查看:196
本文介绍了在C ++中使用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常微不足道的问题,关于在C ++中使用构造函数。我将以面试对话的形式(很难以任何其他形式表示)



面试官 - 什么是构造函数?

me - 构造函数是确保所有对象在使用之前都已初始化的特殊函数。



面试官 - 什么是初始值列表?

我 - 其中所有的初始化发生。



访问者:在所有数据成员初始化之后才输入构造函数的主体意味着在初始化器列表中执行初始化,而不是在构造函数内。但是你说构造函数初始化对象!不是吗?你想回答我的第一个问题。

我 - 我认为构造函数执行赋值,它已经对已经初始化的成员对象调用赋值运算符。



所以我的问题可以是



初始值列表的工作原理



函数的起始地址和[{]?



或者只是回答我如何说服我的面试官。



初始化对象的成员是不是

/ em>与初始化对象本身相同的东西。只是因为成员具有正常的值并不意味着对象已经被构造。直到构造函数完成,对象本身未被正确初始化。


This is very trivial question regarding the use of a constructor in C++. I will present in the form of an interview dialogue (it was difficult to present it in any other forms)

interviewer - what is a constructor?
me - constructor are special functions which makes sure that all objects are initialized before their use.

interviewer - what is an initializer list?
me - that is a list where all the initialization happens. A constructor's body is entered only after all the data members are initialized, or some constructor of all the member objects are called.

interviewer - that means initialization is carried out in initializer list, not inside constructor. But you said constructor initialize the object! Didn't you? Do you want to answer my first question.
me - I think constructor does assignment, it calls assignment operator on already initialized member objects.

So my question to you can be

how initializer list works?

what lies between function's starting address & starting braces [{]?

or just answer me how to convince my interviewer.

解决方案

You're overthinking it and allowing the interviewer to confuse you.

Initializing the members of an object is not the same thing as initializing the object itself. Just because the members have sane values doesn't mean the object has been constructed. Until the constructor has completed, the object itself has not been properly initialized.

这篇关于在C ++中使用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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