Spec-Zone.ru › Octave 9

Предыдущая: Наследование, Вверх: classdef Классы [Оглавление][Индекс]

34.6.5 Классы значений против классов обращений ¶

Существуют два принципиально разных типа classdef классов, основное различие которых заключается в поведении при присваивании переменных. Первый тип — это классы значений:

classdef value_class
  properties
    prop1
  endproperties

  methods
    function obj = set_prop1 (obj, val)
      obj.prop1 = val;
    endfunction
  endmethods
endclassdef

Присваивание объекта этого класса другой переменной фактически создает новый объект:

>> a = value_class ();
>> a.prop1 = 1;
>> b = a;
>> b.prop1 = 2;
>> b.prop1
⇒ ans =  2
>> a.prop1
⇒ ans =  1

Но это также означает, что вам, возможно, придется вручную присваивать результат метода, изменяющего свойства, обратно объекту:

>> a = value_class ();
>> a.prop1 = 1;
>> a.set_prop1 (3);
⇒ ans =

<object value_class>

>> ans.prop1
⇒ ans =  3
>> a.prop1
⇒ ans =  1

Второй тип — это классы обращений. Эти классы должны быть получены от абстрактного handle класса:

classdef handle_class < handle
  properties
    prop1
  endproperties

  methods
    function set_prop1 (obj, val)
      obj.prop1 = val;
    endfunction
  endmethods
endclassdef

В следующем примере переменные a и b ссылаются на один и тот же объект класса handle_class:

>> a = handle_class ();
>> a.prop1 = 1;
>> b = a;
>> b.prop1 = 2;
>> b.prop1
⇒ ans =  2
>> a.prop1
⇒ ans =  2

Свойства объекта, которые изменяются методом класса обращений, изменяются постоянно:

>> a.set_prop1 (3);
>> a.prop1
⇒ ans =  3

Предыдущая: Наследование, Вверх: classdef Классы [Оглавление][Индекс]

© 1996–2023 The Octave Project Developers
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://docs.octave.org/v9.2.0/Value-Classes-vs_002e-Handle-Classes.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API