[英]MATLAB OOP : How do I call a method on an object of class A from inside a method in an object of class B?
語言:
我在MATLAB中編寫面向對象的代碼。 我寫了幾乎所有的內容,現在在嘗試測試時,我遇到了一個非常基本的問題。
背景代碼:
我有一個類Window和一個類跟蹤器。 兩者都是Singleton類的子類(也就是說,它們具有私有構造函數,以確保只創建一個類Window和類Tracker的單個實例)。
我實例化每一個 - 所以我現在有一個myWindow和myTracker對象。
在我的主腳本中,我調用了一個方法myWindow.isNewbead()。 isNewbead是類Window的公共方法。
那是場景。 現在的問題是:
問題:
在isNewbead()中,我調用myTracker.getpredictedPositions()。 getpredictedPositions()是Tracker類的公共方法。 但是,當我運行這一行時,我得到一個錯誤,說變量'myTracker'未定義。 當然,我查看變量工作空間,唯一的變量是局部變量INSIDE myWindow.isNewbead();
所以我現在有兩個問題:
問題:
OOP到處都是這樣嗎? 也就是說,你不能從另一個對象的方法內部調用對象的公共方法而不顯式地將第一個對象傳遞給第二個對象的方法嗎? 這對我來說似乎很麻煩,因為我在每個方法中都使用了許多不同類對象的屬性和方法,所以每次都要經過數百個對象!
如果這只是一個特定於MATLAB的問題(比如無靜態變量的問題),那么我該如何解決這個問題呢?
非常感謝!
問候。
對於Singleton,模式需要“一種機制來訪問單例類成員而不創建類對象”。 如果你正在傳遞課程的實例,你做錯了。 這是一個使用靜態類和全局appdata空間的Matlab實現。 還有另一個實現 ,它具有來自File Exchange的抽象父級,但它將被clear classes
刪除。 選擇你的毒葯。
classdef MySingleton < handle
%
%SingletonParent - A class to limit the instances created to one.
%
%There is a problem with matlab:
% clear classes will clear just about any instance, even those stored in
% persistent variables inside of functions. This would close any opened singletons
% To work around this, we have a method that creates an instance and assigns
% it to the appdata structure. This instance can be explicitly killed, but
% clear all and clear classes will not kill it. If you ever clear classes,
% you will get several messages of this flavor:
%
% Warning: Objects of 'MySingleton' class exist. Cannot clear this
% class or any of its super-classes.
%
% because of the way we assign and store the singleton, you cannot make
% this an abstract parent
%
% Also, any intialization must be done after you get the instance, since you
% have to be able to create it without any data.
%
properties (Constant)
APP_DATA_NAME = 'MySingleton';
end %properties
methods (Access = private)
function obj = MySingleton()
%initialization code.
%must be private to ensure getInstance call is the only link into it.
end %Singleton
end%private methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods (Static)
function out = getInstance()
%getInstance - get/creates Singleton
%
% stores the instnace such that it is immune to clear all/clear classes
%
%out = getInstance
%Returns
% singleton instance. if it does not exist, creates a default one, or passes the data to the ctor
if ~isappdata(0, MySingleton.APP_DATA_NAME);
obj = MySingleton;
setappdata(0, MySingleton.APP_DATA_NAME, obj);
end
out = getappdata(0, MySingleton.APP_DATA_NAME);
end %getMasterInstance()
end %static methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
methods
%public methods that it uses to work.
end %PublicMethods
end %MySingleton Class
是的,你可以從另一個對象(對象B)的方法調用一個對象(對象A)的公共方法,因為它是公共的; 但是,您需要在對象B方法中使用對象A的引用。 將對象A的引用作為對象B方法的輸入參數傳遞。
這可能看起來很麻煩,但這怎么可能呢? 盡管Tracker繼承自Singleton類,但myTracker仍然只是Tracker對象的一個實例 。 您需要對此實例的引用才能使用其方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.