Main Content

用户定义的类

What Is a Class Definition

A MATLAB®class definition is a template whose purpose is to provide a description of all the elements that are common to all instances of the class. Class members are the properties, methods, and events that define the class.

Define MATLAB classes in code blocks, with subblocks delineating the definitions of various class members. For syntax information on these blocks, seeComponents of a Class.

Attributes for Class Members

Attributes modify the behavior of classes and the members defined in the class-definition block. For example, you can specify that methods are static or that properties are private. The following sections describe these attributes:

Class definitions can provide information, such as inheritance relationships or the names of class members without actually constructing the class. SeeClass Metadata.

SeeSpecifying Attributesfor more on attribute syntax.

Kinds of Classes

There are two kinds of MATLAB classes—handle classes and value classes.

  • Value classes represent independent values. Value objects contain the object data and do not share this data with copies of the object. MATLAB numeric types are value classes. Values objects passed to and modified by functions must return a modified object to the caller.

  • 处理类创建引用对象数据的对象。实例变量的副本是指同一对象。处理对象传递给并通过功能修改的对象会影响呼叫者工作区中的对象,而无需返回对象。

For more information, seeComparison of Handle and Value Classes.

Constructing Objects

For information on class constructors, seeClass Constructor Methods.

For information on creating arrays of objects, seeConstruct Object Arrays.

Class Hierarchies

For more information on how to define class hierarchies, seeHierarchies of Classes — Concepts.

classdef Syntax

Class definitions are blocks of code that are delineated by theclassdefkeyword at the beginning and theendkeyword at the end. Files can contain only one class definition.

The following diagram shows the syntax of aclassdefblock. Only comments and blank lines can precede theclassdefkeyword.

Class Code

Here is a simple class definition with one property and a constructor method that sets the value of the property when there is an input argument supplied.

classdefMyClass特性Propendmethodsfunctionobj = MyClass(val)ifnargin > 0 obj.Prop = val;endendendend

To create an object ofMyClass, save the class definition in a.mfile having the same name as the class and call the constructor with any necessary arguments:

d = datestr(now); o = MyClass(d);

Use dot notation to access the property value:

o.Prop
ans = 10-Nov-2005 10:38:14

The constructor should support a no argument syntax so MATLAB can create default objects. For more information, seeNo Input Argument Constructor Requirement.

For more information on the components of a class definition, seeComponents of a Class

相关话题