How to avoid using a global variable in this case
显示 更早的评论
Dear all,
I have the following problem. I wrote some code where I overload various operators (+ - * /) and I would like to keep track of all the operations done. I initialize a session by creating a global variable, "myglobal", which will help me in this endeavor.
global myglobal
myglobal=containers.Map();
Then the typical overloaded operation does the following
function c=plus(a,b)
c=myobject(a.x+b.x);
push(c)
end
where the push function above roughly looks like this
function push(c)
global myglobal
Count=myglobal.Count+1;
myglobal(Count)=c.x;
end
I know using global variables is bad and I would like to get rid of the global variable. Any suggestion on how to go about this?
Thanks,
Pat.
2 个评论
Walter Roberson
2013-3-26
Is the counter to be per-class or per-object ?
Patrick Mboma
2013-3-26
采纳的回答
更多回答(1 个)
Cedric
2013-3-26
I thought that you were talking about OOP with your initial question, but if not, it is not a good idea to overload common operators.
A handle class would certainly make everything easier.. e.g.
classdef MBoma < handle
properties
value
history = {}
end
methods
function self = MBoma(value)
self.value = value ;
end
function c = plus(self, b)
if isa(b, 'MBoma')
c = MBoma(self.value + b.value) ;
self.push('plus', b.value) ;
b.push('plus', self.value) ;
else
c = self.value + b ;
self.push('plus', b) ;
end
end
function push(self, id, value)
self.history = [self.history; {id, value}] ;
end
end
end
With that,
>> a = MBoma(5) ;
>> b = MBoma(7) ;
>> c = a + 9
c =
14
>> d = a + b
d = MBoma handle
Properties:
value: 12
history: {}
>> a.history
ans =
'plus' [9]
'plus' [7]
>> b.history
ans =
'plus' [5]
>> d.history
ans =
{}
类别
在 帮助中心 和 File Exchange 中查找有关 Standard File Formats 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!