ruby 构造函数_Ruby| 如何在派生类对象的帮助下初始化基类构造函数?
ruby 构造函数
During inheritance, if you want to provide values to the base class constructor with the help of derived class object then you are in need to make use of "super" keyword. By implementing super() in the initialize method of the subclass, you can initialize variables of the base class.
在继承期间,如果要在派生类对象的帮助下为基类构造函数提供值,则需要使用“ super”关键字 。 通过在子类的initialize方法中实现super() ,可以初始化基类的变量。
The following are the cases related to super,
以下是与超级相关的情况,
super with no arguments:
超级无参数 :
When you only write
当你只写
"super" that simply means you are invoking super with no arguments. In such case, Ruby gives a message to the superclass of that object and asks it to invoke the same name method in Base class as the method calling super.
“ super”仅表示您在不带参数的情况下调用super。 在这种情况下,Ruby将消息传递给该对象的超类,并要求它在基类中调用与调用super的方法相同的名称方法。
super with the vacant list:
超级空缺名单 :
The implementation looks like
实现看起来像
super(), in this case and no argument is passed to the Parent class of that object even if the base class constructor is having some supplied values in the parameter list.
super() ,在这种情况下,即使基类构造函数在参数列表中具有一些提供的值,也不会将任何参数传递给该对象的Parent类。
super with argument list:
带有参数列表的超级 :
The general implementation looks like
一般的实现看起来像
super(val1, val2, ..., valn) in this case. Here all the arguments will be passed to the Superclass which are mentioned in the argument list of super.
在这种情况下为super(val1,val2,...,valn) 。 在这里,所有参数都将传递给super的参数列表中提到的超类。
Code:
码:
=begin How to initialize base class variables with derived class object =end class Base def initialize(a,b) @var1=a @var2=b puts "Value of a and b is #{@var1} and #{@var2} in base class" end end class Derived < Base def initialize(a,b) super(a,b) #implementation of super @var3=a @var4=b end def print1 puts "Value of a and b is #{@var3} and #{@var4}" end end ob1=Derived.new(10,20) ob1.print1[/code]
Output
输出量
Value of a and b is 10 and 20 in base class Value of a and b is 10 and 20[/code]
You can observe in the above code that we are passing arguments in the super() method and those arguments are passed to the Superclass by Ruby resulting in the initialization of Superclass variables.
您可以在上面的代码中观察到我们在super()方法中传递参数,并且这些参数由Ruby传递给超类,从而导致超类变量的初始化。
ruby 构造函数
- 多重继承、虚基类继承时,显式地调用基类构造函数,对象是如何初始化的问题
- 多重继承、虚基类继承时,没有显式调用基类构造函数,对象是如何初始化的问题
- C++中基类,派生类 类成员对象的构造函数,析构函数的顺序
- C++如何在派生类成员函数内调用基类的成员函数(包括构造函数)
- 关于c++中派生类构造函数初始化基类的记录
- C++派生类对象构造函数初始化顺序
- 【C++】派生类对象初始化基类的引用
- 派生类的构造函数及其对象的初始化
- C++派生类中如何初始化基类对象
- 派生类的构造函数、对象的初始化
- C++派生类中如何初始化基类对象
- 派生类的构造函数对基类显示初始化
- C++派生类中如何初始化基类对象
- 派生类的构造函数及其对象的初始化
- 【提问整理】protected继承,派生类对象如何访问基类成员?
- C++派生类中如何初始化基类对象
- 多重继承时非虚基类继承对象是如何初始化的问题
- 基类的构造函数带参数,如何定义其派生类
- 虚基类继承与非虚基类继承时对象是如何初始化问题
- 派生类的构造函数中,可以将基类作为成员变量进行初始化