Why objects are losing reference for each other?

2 ビュー (過去 30 日間)
Hudson Romualdo
Hudson Romualdo 2022 年 9 月 18 日
移動済み: Matt J 2022 年 9 月 20 日
Hello.
I'm wrinting a code in using O.O. paradigm and having some problems with references.
I have one classe "Person" that have to be conected with other people (objets of Person)
The problem is that when I navegate deep in the connections, some Person loose it's connection. When I access the object in the "first level" there is the connection. But accessing the same person in a second level, there is no connection anymore.
Here is the code:
classdef Pearson
properties
connections
end
properties(Access = private)
connIndex = 1;
end
methods
function obj = Pearson()
obj.connections = cell(3:1);
end
function obj = addConnection(obj, person)
obj.connections{obj.connIndex} = person;
obj.connIndex = obj.connIndex + 1;
end
end
end
close all; clear; clc;
people = cell(3:1);
%Creating 3 people
for p = 1:3
people{p} = Pearson();
end
%Creating connections between them
people{1} = people{1}.addConnection(people{2});
people{1} = people{1}.addConnection(people{3});
people{2} = people{2}.addConnection(people{1});
people{3} = people{3}.addConnection(people{1});
I'm doing something wrong?

採用された回答

chrisw23
chrisw23 2022 年 9 月 20 日
移動済み: Matt J 2022 年 9 月 20 日
try this
classdef Pearson < handle
...
function addConnection(obj, person)
obj.connections{obj.connIndex} = person;
obj.connIndex = obj.connIndex + 1;
end
  1 件のコメント
Hudson Romualdo
Hudson Romualdo 2022 年 9 月 20 日
移動済み: Matt J 2022 年 9 月 20 日
Thanks @chrisw23.
It worked!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeHandle Classes についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by