Class definition: is it necessary to define properties as struct?

조회 수: 6 (최근 30일)
Xh Du
Xh Du 2017년 3월 13일
편집: Adam 2017년 3월 13일
Hi all,
I'm new to OOP in MATLAB. When defining properties in a class, shall I define them as constants or as a struct? For example, explicitly:
classdef myClass < handle
properties
a
b
c
end
methods
function obj = myClass(a, b, c)
obj.a = a;
obj.b = b;
obj.c = c
end
end
or as struct
classdef myClass < handle
properties
prop
end
methods
function obj = myClass(a, b, c)
obj.prop.a = a;
obj.prop.b = b;
obj.prop.c = c;
end
end
The first way allows me to define attributes, such as private, public, etc. But if there are lots of properties, this way is too long.
The second way I will only be able to define attributes for the entire 'prop', I cannot only define prop.a as private but prop.b and prop.c as public, but the second way seems very neat.
What do you usually do and why?
Thank you!

채택된 답변

Adam
Adam 2017년 3월 13일
편집: Adam 2017년 3월 13일
The whole point of a class is that it is an extended and far better version of a struct (apart from performance-wise). Properties of a class are analagous to fields of a struct. Think of your class as a replacement for the struct, not something to combine with it.
With good OOP design you should never have a single class that has so many properties you have trouble typing them out anyway.
I have never yet used a struct inside a class as it defeats the purpose. The properties of a class are visible, the fields of a struct could be anything.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Class File Organization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by