Entries in array of class instances affecting others in my array

조회 수: 1 (최근 30일)
Rosco Hunter
Rosco Hunter 2020년 4월 5일
댓글: Rosco Hunter 2020년 4월 5일
I can't understand why changing instances of a class in an array effect the other entires.
An example of how this works is as follows:
I create a class as follows in one file:
classdef Terminal < handle
properties
Point_1=[]
Point_2=[]
end
end
And wish to make an array where the entires are instances of this class which I create in another file:
%The line below is to make an array with 3 entires all of which are instances of the class Terminal
Terminal_array(1:3)=Terminal
Terminal_array(1).Point_1=1;
%If I call here 'Terminal_array(1).Point_1' the output is 1
Terminal_array(2).Point_1=2;
Terminal_array(3).Point_1=3;
Terminal_array(1).Point_1
If I call Terminal_array(1).Point_1 at the bottom it is 3 instead of the desried 1. I can't understand why this is happening.
Any help or advice would be appriciated.

채택된 답변

Steven Lord
Steven Lord 2020년 4월 5일
You're assigning the same handle object to all three elements of Terminal_array. That means changing one of the elements of Terminal_array will change all of them. You can see that they refer to the same object using the == operator as described on this documentation page.
Terminal_array(1:3) = Terminal;
Terminal_array(1) == Terminal_array(2) % true
Terminal_array(1) == Terminal_array(3) % true
If you created the elements of the array through separate calls to the constructor, they would not refer to the same object.
Terminal_array2(1) = Terminal;
Terminal_array2(2) = Terminal;
Terminal_array2(3) = Terminal;
Terminal_array2(1) == Terminal_array2(2) % false
Terminal_array2(1) == Terminal_array2(3) % false
Terminal_array2(2) == Terminal_array2(3) % false

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by