Class method calls method of other instantiated class

조회 수: 2 (최근 30일)
Nico Lehmann
Nico Lehmann 2019년 3월 11일
댓글: Nico Lehmann 2019년 3월 18일
Hello everyone,
I'm new to OOP and have a question.
I have the following class:
classdef Operator
properties
id;
offer;
end
methods
% Functions
function submitOffer(obj)
% submit offer
centralMarket.enterOffer(obj.offer);
end
end
An instance of this class shall pass the variable "offer" to an instance of the class "CentralMarket".
classdef CentralMarket
properties
id;
orderBook;
marketResult;
end
% Functions
function obj = enterOffer(obj, offer)
% write offer into the order book
w_idx = length(obj.orderBook) + 1;
obj.orderBook{w_idx} = offer;
end
For this I call the function "submitOffer" of the initialized class "Operator":
operator.submitOffer();
But it's not working out the way I want it to. I get the following message:
Undefined variable "centralMarket" or class "centralMarket.enterOffer".
Of course, I can work around the whole thing as follows:
centralMarket = centralMarket.enterOffer(operator.offer);
But that wouldn't be pleasant. Is there a way?

채택된 답변

Steven Lord
Steven Lord 2019년 3월 11일
If the object stored in the offer property of the Operator class is a CentralMarket object, this should work.
function submitOffer(obj)
enterOffer(obj.offer);
end
If it is not a CentralMarket object, but the enterOffer method of the CentralMarket object were a Static method, that could work.
classdef CentralMarket
% ...
methods(Static)
function obj = enterOffer(obj, offer)
% ...
end
end
end
But because enterOffer manipulates properties of the obj object passed into it as input, it's probably not suitable to be a Static method.
You might want to read through the BankAccount and AccountManager classes on this documentation page. You may be able to use them as a model for your application. Alternately, explain in more detail (in words not code) how you want the Operator class method submitOffer and the CentralMarker class to interact with one another and we may be able to help you figure out the best way to implement that interaction.
  댓글 수: 1
Nico Lehmann
Nico Lehmann 2019년 3월 18일
Thank you very much for the quick answer!
As you already said, the objects localMarket and centralMarket must be passed to the instance of the class "Operator" operator. It is important that both objects are handle classes so that no copies are made. Your linked tutorial with the bank account helped a lot here.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by