2016-07-30 53 views
1

我正在尝试使用MATLAB OOP。我想更改类构造函数中的类方法处理程序。 例如,我有一个类test其中一类方法使用的取决于可变number类性质的方法之一:是否有可能在MATLAB中改变方法功能处理程序classdef

mytest = test(2); 
mytest.somemethod(); 

classdef test < handle 
    properties 
    number 
    end 
    methods   
    function obj = test(number) 
     obj.number = number; 
    end 
    function obj = somemethod(obj) 
     switch obj.number 
     case 1 
      obj.somemethod1(); 
     case 2 
      obj.somemethod2(); 
     case 3 
      obj.somemethod3(); 
     end 
    end 
    function obj = somemethod1(obj) 
     fprintf('1') 
    end 
    function obj = somemethod2(obj) 
     fprintf('2') 
    end 
    function obj = somemethod3(obj) 
     fprintf('3') 
    end 
    end 
end 

这里使用switch操作者每当test.somemethod()被调用。我可以使用switch曾经只在类的构造函数初始化的时间(即改变方法处理)如下:

classdef test < handle 
    properties 
    number 
    somemethod %<-- 
    end 
    methods 
    % function obj = somemethod(obj,number) % my mistake: I meant the constructor 
    function obj = test(number) 
     obj.number = number; 
     switch number 
     case 1 
      obj.somemethod = @(obj) obj.somemethod1(obj); 
     case 2 
      obj.somemethod = @(obj) obj.somemethod2(obj); 
     case 3 
      obj.somemethod = @(obj) obj.somemethod3(obj); 
     end 
    end 
    function obj = somemethod1(obj) 
     fprintf('1') 
    end 
    function obj = somemethod2(obj) 
     fprintf('2') 
    end 
    function obj = somemethod3(obj) 
     fprintf('3') 
    end 
    end 
end 

这第二个实施test类不起作用。 对于S = test(2); S.somemethod(),出现错误: 错误使用测试> @(obj)obj.somemethod2(obj)(行...) 输入参数不足。 有什么问题?

回答

2

首先,你不能有somemethod作为方法属性。您可以摆脱该方法,并为您的构造函数中的属性指定一个函数句柄。

function self = test(number) 
    self.number = number; 
    switch self.number 
     case 1 
      self.somemethod = @(obj)somemethod1(obj) 
    %.... 
    end 
end 

而且,当前的匿名函数你传递的对象的方法的副本:

  1. obj.method隐含通过obj作为第一个输入
  2. obj.method(obj)传递的第二个副本作为第二输入的obj

您想更新您的对象句柄,如下所示,它会将obj的单个副本传递给该方法。

obj.somemethod = @obj.somemethod3 

此外,使用你的类时,你就必须使用点符号,因为它是一个属性,而不是一个“真实”的方法

S = test() 
S.somemethod() 
+0

有关属性和方法是相同的名称来执行somemethod是我的类型错误(我的意思是在构造函数中初始化)。但'S = test(2); S.somemethod()'生成错误:“错误使用测试> @(obj)obj.somemethod2(obj)没有足够的输入参数。” –

+0

@AlexanderKorovin对不起,我打错了。应该现在工作 – Suever

+0

谢谢!不幸的是,我发现这个实现('obj.somemethod = @ obj.somemethod3')比使用'switch'大约慢两倍! –

相关问题