为什么我们需要 OOP 中的构造函数? [英] Why do we need a constructor in OOP?
问题描述
我是面向对象编程的新手.我还在学习阶段.
I am new to OOP. I am still in a learning phase.
为什么需要构造函数,什么时候可以通过编写初始化函数"来初始化属性(变量)的值?
Why do we need constructors, When we can initialize the values of the properties (variables) by writing a "Initialize function"?
当我们编写一个初始化变量的函数也能获得相同的结果时,基本上为什么我们还要编写一个构造函数?
Basically why do we write a constructor when we can achieve the same results even by writing a function for initializing the variables?
推荐答案
构造函数就是初始化函数"
The constructor IS the "Initialize function"
而不是调用两个函数
object = new Class;
object.initialize();
你只要打电话
object = new Class();
构造函数内部的逻辑可以与 initialize 函数内部的逻辑相同,但它更整洁,避免了你命名你的函数 initialize(),我命名我的 initialize_variables(),以及其他人命名他们的 init_vars().. 一致性很有用.
The logic inside the constructor can be identical to the logic inside the initialize function, but it's much tidier and avoids you naming your function initialize(), me naming mine initialize_variables(), and someone else naming theirs init_vars()... consistency is useful.
如果您的构造函数非常大,您可能仍希望将变量初始化拆分为一个单独的函数并从您的构造函数调用该函数,但这是该场景的特定例外.
If your constructor is very large, you may still wish to split variable initialisation into a separate function and calling that function from your constructor, but that's a specific exception to the scenario.
这篇关于为什么我们需要 OOP 中的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!