storing multiple objects derived from two different classes in one array

조회 수: 11 (최근 30일)
I have two objects, lets say user_1 and user_2 that do not belong to the same class, I want to know if it is possible to store them in the same array.
  댓글 수: 2
KSSV
KSSV 2019년 3월 4일
On what context of data you are talking about?
Afaf Arfaoui
Afaf Arfaoui 2019년 3월 4일
Actually I have defined one class called "User" after that I realized that I will need to define 2 types of users using two classes, lets say UserType1 and UserType2.
The problem is that my code was working using an array of users of the old class "User" only. When I defined two seperate classes I wasn't able to store the users of different classes in the same array and all my code was about this array.

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

채택된 답변

Matt J
Matt J 2019년 3월 4일
편집: Matt J 2019년 3월 4일
I want to know if it is possible to store them in the same array.
Yes, if that array is a cell array. Cell arrays can store any mixture of types,
array={user_1, user_2}
  댓글 수: 3
Afaf Arfaoui
Afaf Arfaoui 2019년 3월 4일
Okay I see. I've tried the suggestion of Steven Lord in the comment below and it's working using a simple array. The class of the array is the super class 'User' but it contains objects from different classes that inherit from the super class. Thanks for your help!

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

추가 답변 (1개)

Steven Lord
Steven Lord 2019년 3월 4일
If those objects are in the same class hierarchy, you could make the hierarchy heterogeneous.
  댓글 수: 2
Afaf Arfaoui
Afaf Arfaoui 2019년 3월 4일
No but I can define a super class from which the other two classes can inherit. Thank you.

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

카테고리

Help CenterFile 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!

Translated by