필터 지우기
필터 지우기

Calling setter with a third argument?

조회 수: 6 (최근 30일)
markushatg
markushatg 2012년 10월 3일
In a class with the dependent property c, I would like to call c's setter with a third argument that equals 'a' or 'b', choosing which independent property to alter in order to set c.
the code is
classdef test < handle
properties
a
b
end
properties (Dependent = true)
c
end
methods
function c = get.c(obj)
c = obj.a + obj.b;
end
function obj = set.c(obj, value, varargin)
if(nargin == 2)
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'a') % how do I enter this loop?
obj.a = value - obj.b;
end
if(nargin == 3 && argin(3) == 'b') % or this?
obj.b = value - obj.a;
end
end
end
end
This call works:
myobject.c = 5
But how do i call the setter with a third parameter equaling 'a' or 'b'?
Thanks

답변 (1개)

Daniel Shub
Daniel Shub 2012년 10월 3일
You can't. The set function can only take two arguments. You cannot change the function footprint. Even if you could change the function footprint, how would you call the set function?
You can cheat in three ways
The first is to call the set function with a cell array (or a structure ...)
myobject.c = {5, 'a'}
and then check if the input is a 2-element cell with one value equal to 'a' or 'b'. This of course assumes that you never actually want to set c to be {5, 'a'}. I would say that this is not a good solution.
The second would be to define a mysetc method identical to your set.c method and let this method do the setting. If you go this route you want to make the SetAccess for c to be private. This method means users need multiple interfaces for setting properties.
The third method builds on the second method. Define a set method.
function set(obj, property, value, varargin)
that parses the property to determine which set.x method to call. this means users would always use set(obj, prop, value). You could overload subsassgn to handle simple cases like myobj.c = 5
Note that the syntax for argin(3) is usually varargin{3}. Also handle class set methods do not return a value, but object class methods do.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by