Class method calls method of other instantiated class
조회 수: 2 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!