Error-Variable might be used before it is defined

3 ビュー (過去 30 日間)
Milad Bahaedini
Milad Bahaedini 2022 年 11 月 20 日
コメント済み: Steven Lord 2022 年 11 月 22 日
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 件)

カテゴリ

Help Center および File ExchangeSpecifying Target for Graphics Output についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by