필터 지우기
필터 지우기

Constructor doesn`t work at all (Error using implicit default value of property in class)

조회 수: 5 (최근 30일)
I tried to initialize class properties but got error
"Error using implicit default value of property in class 'val1'. Value must greater than 0"
first I have made an example class
classdef myclass
properties (access = public)
val1 double {mustBeGreaterThan(val1,0)};
end
properties (access = private)
val2 double {mustBeGreaterThan(val2,0)};
end
methods
function obj = myclass()
%constructor
if nargin<1
obj.val1 = 0.3;
obj.val2 = 0.5;
end
end
end
end
after making class, implement the codes
myclass_instance = myclass()
and it says error
"Error using implicit default value of property 'var1' in class 'myclass'. Value muse be greater than 0
why I got an error message? Is the property constraints are called faster than the constructor?
Then the only solution is to remove constraints?
What a mess language matlab it is!

채택된 답변

Matt J
Matt J 2023년 1월 13일
편집: Matt J 2023년 1월 13일
Your posted code produces an error, but not the one you claim. You've misspelled the "Access" attribute, but once that is fixed (see attached), the class instantiates as expected,
obj=myclass()
obj =
myclass with properties: val1: 0.3000
  댓글 수: 1
Steven Lord
Steven Lord 2023년 1월 13일
I saw the same behavior as Matt J with the posted code in release R2022b. I suspect you may be using an older release and/or that you've specified a default value that doesn't satisfy your validator, though when I tried that I received a slightly different error message.
Rather than setting default values for the properties in the constructor, why not just set them in the property definitions themselves? Something along the lines of the attached. I added in a method to let us inspect the private property.
No inputs gives us the default values:
y = myclass
y =
myclass with properties: val1: 0.3000
displayVal2(y)
ans = 0.5000
1 input sets val1 but leaves val2 at the default.
y = myclass(1)
y =
myclass with properties: val1: 1
displayVal2(y)
ans = 0.5000
2 inputs sets both val1 and val2.
y = myclass(1, 2)
y =
myclass with properties: val1: 1
displayVal2(y)
ans = 2

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by