Class and Object Creation, forcing argument types

조회 수: 3 (최근 30일)
Mark
Mark 2014년 10월 9일
편집: Matt J 2014년 10월 9일
I've made a user defined class, and I want to ensure that the arguments passed to the class constructor are of a certain variable type, and to not create an instance/object unless they are correct variable types. I have the constructor checking to see if it is a certain variable type, displaying some text saying it needs to be a certain type, and returning if it is not, but it still creates an object with empty properties. Anyone know how to prevent this? See my example below
classdef example
properties
exampleProp
end
methods
function exam = example(argument)
if ~isa(argument,'string)
disp('Argument needs to be a string')
return
end
exampleProp = argument;
end
end
My script would call
a = example(7)
Display my message and say 'Argument needs to be a string' but then i'd get an object with
a =
example
Properties:
exampleProp = []
But I don't want 'a' in this case. Any info is appreciated.
  댓글 수: 1
Mark
Mark 2014년 10월 9일
I just realized my ultimate goal is to not create an object unless the argument is a specific value, e.g. if argument == 'this string' and not if argument == 'that string'.
Thanks

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2014년 10월 9일
편집: Matt J 2014년 10월 9일
"Constructors must always return a valid instance of the class."
You cannot have a class constructor returning nothing. Furthermore, any time you have any kind of function call in MATLAB
a=someFunction(...)
you must return an output argument that can be held in "a". Only function calls that don't request any outputs are permitted to return no outputs, e.g.,
plot(t,x)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by