【问题标题】:Class property not set by function函数未设置类属性
【发布时间】:2020-12-18 11:57:59
【问题描述】:

我正在使用 MATLAB 类并遇到属性问题。

我调用的代码是

theory = ODtheory;
theory.enableDebug(true);
theory.captureRange();

最后一个函数应该打印出值,因为调试设置为true

这是类的代码:

    function obj = ODtheory(~)
        obj.isDebug = false;
    end
    
    function obj = enableDebug(obj,value)
        obj.isDebug = value;
    end

但在function range = captureRange(obj) 中,变量(属性)obj.isDebug 仍设置为 false。

function range = captureRange(obj)
   ...
   if obj.isDebug; disp(['FOW: ' num2str(round(FOW,1)) '/mm']); end
end

【问题讨论】:

    标签: matlab class properties


    【解决方案1】:

    我假设您的 ODtheory 类是 value class,因此您需要将其分配回自身以注册对象属性的更改。

    例如:

    theory = ODtheory;
    theory = theory.enableDebug(true);
    theory.captureRange();
    

    如果您的 captureRange 函数还修改了对象属性,您也应该使用

    theory = theory.captureRange();
    

    另一种方法是将类设为handle 类(参见上面的链接)

    classdef ODtheory < handle
    %  ... class definition here ...
    end
    

    然后你可以使用你的原始代码而不用赋值。

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多