Error-Variable might be used before it is defined

조회 수: 6(최근 30일)
I have defined some classes and two of them Called "Global" &"GlobalFlag".
All the classes are in one folder and same path.
But I got this warning that the "Variable might be used befire it is defined" and also after running I get the error " Global is not found in the current folder or on the MATLAB path, but exists in:"
Everything looks correct.
Any idea?
In this screenshot Die is also an object of a class.

채택된 답변

Steven Lord
Steven Lord 2022년 11월 20일
This would work if SpeedMaxOpt is a Constant property of the Global class or a Static method of that class that can be called with 0 input arguments. But if SpeedMaxOpt is a regular (non-Constant) property or a regular (non-Static) method it needs to be associated with an instance of the object.
As a simple example, if you had a Human class it wouldn't make sense to ask Human.hairColor. Individual Human objects may have varying hairColor property values -- 'red', 'black', even 'none'. But if Human had a property isMammal we wouldn't need to know to which Human you're referring -- all Human objects will return true for isMammal.
Or in terms of methods, at least as far as we know we don't need to know which Human you're asking about when you ask what the closestStar is to the Human. No known Human is closer to another star than they are to the Sun.
classdef Human
properties % NOT Constant
hairColor
end
properties(Constant)
isMammal = true;
end
methods(Static)
function starName = closestStar
starName = 'the Sun';
end
end
end
With that code above, the first two of these lines of code would work. The third wouldn't. I suspect you're in the third scenario.
y = Human.isMammal
s = Human.closestStar
z = Human.hairColor
Here's what I get when I run those three lines in my MATLAB session.
>> y = Human.isMammal
y =
logical
1
>> s = Human.closestStar
s =
'the Sun'
>> z = Human.hairColor
The property 'hairColor' in class 'Human' must be
accessed from a class instance because it is not a
Constant property.
  댓글 수: 1
Steven Lord
Steven Lord 2022년 11월 22일
If the Global class has no properties, what is SpeedMaxOpt? Is it a method of the Global class? If it is, does it require an instance of the class on which to operate (like if I had a getHairColor method on the Human class) or should it be Static (like closestStar)?
If the former, if it requires an instance, what you've written won't work. You would need to first create an instance of the Global class then call the method with that object as input, either as:
y = Global;
s = y.SpeedMaxOpt;
or
y = Global;
s = SpeedMaxOpt(y);

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

추가 답변(0개)

범주

Find more on Construct and Work with Object Arrays in Help Center and File Exchange

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by