也許這是一個微不足道的問題,但我想知道如何訪問類建構式中的常量屬性或八度音階中的類函式。讓我們舉個例子:
classdef Example % < FatherClass
% read-only protected properties
properties (Constant=true, Access=protected)
all_levels = {"A","B","C","D"};
endproperties
% protected properties
properties(Access=protected)
level = 'D';
output = '.';
endproperties
methods(Access=public)
function obj = Example (level,outputfilepath)
if any(strcmp(all_levels,level))
obj.level = level;
else
error ("possible levels are: A B C D");
endif
obj.output = outputfilepath
endfunction
endmethods
end
運行此類示例我收到錯誤:
error: 'all_levels' undefined near line 12, column 12
error: called from
Example at line 12 column 13
所以,我嘗試過類似的東西
if any(strcmp(obj.all_levels,level))
obj.level = level;
結果相同,還定義了一個 getter:
methods (Static = true)
function lvs = gel_levels()
lvs = all_levels
endfunction
endmethods
...
methods(Access=public)
function obj = Example (obj,level,outputfilepath)
all_levels = get_levels()
% disp(all_levels)
if any(strcmp(all_levels,level))
obj.level = level;
else
error ("possible levels are: A B C D");
endif
obj.output = outputfilepath
endfunction
endmethods
抱歉,我對 octave 很陌生,我還沒有找到任何關于此的示例。我想要完成的是一個簡單的類變數
uj5u.com熱心網友回復:
這個問題有點令人困惑,因為不同的嘗試似乎使用了不同的部分,但總的來說,我認為你的問題是你沒有將物件作為方法中的形式引數傳遞。
也不清楚您是嘗試“就地”修改物件,還是嘗試生成新物件……但無論如何請記住,不可能就地修改物件(除非從“句柄”繼承目的)。因此,您應該做的典型事情是:將物件作為第一個輸入傳入,就像您應該對類方法定義所做的那樣,修改它,回傳它,然后當您在呼叫中使用此方法時作業區,通過賦值捕獲此物件(通常在與呼叫作業區中被呼叫物件同名的變數中)。
這對我有用:
%% in Example.m
classdef Example
% read-only protected properties
properties( Constant=true, Access=protected )
all_levels = {"A", "B", "C", "D"};
endproperties
% protected properties
properties( Access = protected )
level = 'D';
output = '.';
endproperties
methods( Access = public )
function obj = Logging( obj, level, outputfilepath )
valid_level_choice = any( strcmp( obj.all_levels, level ) );
if valid_level_choice, obj.level = level;
else, error( "possible levels are: A B C D" );
endif
obj.output = outputfilepath;
endfunction
function get_level( obj )
fprintf( "The level is %s\n;", obj.level );
endfunction
endmethods
endclassdef
%% In your console session
E = Example();
E.get_level()
%> The level is D
E = E.Logging( 'A', './' );
E.get_level()
%> The level is A
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479310.html
