Entries in array of class instances affecting others in my array

1 次查看(过去 30 天)
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