我正在嘗試創建一個介面,MATLAB 中的其他類將繼承。該介面有一個保存 function_handle 值的屬性。我遇到的問題是,在實體化從此類繼承的具體類時,我收到以下訊息:Error defining property 'MyFuncHandle' of class 'IMyInterfaceClass'. Unable to construct default object of class function_handle.
介面類看起來像這樣:
classdef (Abstract) IMyInterfaceClass < handle
properties (Abstract)
MyFuncHandle(1,1) function_handle
end
methods (Abstract, Access = public)
% Some abstract methods declared here
end
end
另一個類繼承這樣的介面:
classdef (Abstract) MyClassThatInheritsTheInterface < IMyInterfaceClass & SomeOtherAbstractClass
properties
MyFuncHandle
end
methods (Abstract)
% Some abstract methods declared here
end
methods
function this = MyClassThatInheritsTheInterface()
this@SomeOtherAbstractClass();
end
% Some concrete methods declared here
end
end
并且,最終,一個具體的子類繼承自MyClassThatInheritsTheInterface.
我嘗試將屬性宣告更改IMyInterfaceClass為:
properties (Abstract)
MyFuncHandle(1,1) function_handle = function_handle.empty
end
但是,這是行不通的。我也嘗試將其設定為默認值,如下所示:
properties (Abstract)
MyFuncHandle(1,1) function_handle = @ode15s
end
那也行不通。
有沒有辦法讓它作業,同時保持型別MyFuncHandle檢查IMyInterfaceClass?顯然,去掉型別檢查并將其保留為鴨子型別的屬性會消除錯誤,但不能確保屬性中的值是 function_handle。
uj5u.com熱心網友回復:
我認為我們可以稍微提煉一下這個例子來解決這個問題
抽象超類
classdef (Abstract) IMyInterfaceClass < handle
properties
MyFuncHandle(1,1) function_handle = @(varargin) disp([])
end
methods (Abstract, Access = public)
% Some abstract methods declared here
end
end
繼承抽象類的具體類
classdef MyClassThatInheritsTheInterface < IMyInterfaceClass
properties
% Subclass properties
end
methods
function this = MyClassThatInheritsTheInterface()
this@IMyInterfaceClass();
end
% Some concrete methods declared here
end
end
這些幾乎是從您的示例中提取的,除了我跳過了第二層抽象而只使用了一個抽象超類。以下幾點應該仍然適用。
注意MyFuncHandle應該只在抽象超類中指定。
function_handle.empty正如您所料,也是空的。但是,您需要根據您的屬性規范使用 1x1 函式句柄。我所知道的最簡單的“無所事事”功能可以滿足這一點@(varargin) disp([]),它接受任何輸入并且不顯示任何內容。如果沒有被覆寫,您當然可以使用會引發錯誤的東西
@(varargin) error( 'MyFuncHandle has not been defined' );
現在你可以做a = MyClassThatInheritsTheInterface();,你會看到它a.MyFuncHandle已正確初始化。
也許這里的關鍵是,這絕不會試圖將某物歸類為Abstract屬性,同時也給它一個與其抽象不一致的值。
uj5u.com熱心網友回復:
另一種方法是使用驗證函式而不是類/大小約束。我意識到它感覺不太令人滿意,但它可能是一種有用的方法。在這種情況下
properties
SomeFcn {mustBeA(SomeFcn, "function_handle")}
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530884.html
