Main Content

本页翻译不是最新的。点击此处可查看最新英文版本。

classdef

类定义关键字

语法

classdef (Attributes) ClassName < SuperclassNames
    properties (Attributes) ... end
    methods (Attributes) ... end
    events (Attributes) ... end
    enumeration ... end
end

说明

classdef ... end 包含类定义。classdef 模块的第一行采用以下语法:

classdef (Attribute1 = value1, Attribute2 = value2,...) ClassName < 
SuperclassName1 & SuperclassName2 & ...

  • (Attribute1 = value1, Attribute2 = value2,...) - 可选的类属性,指定为属性名称及其关联值的以逗号分隔的列表。例如,以下语法定义一个抽象类,此抽象类包含由允许的子类组成的受限列表:

    classdef (Abstract = true, AllowedSubclasses = {ClassA, ClassB}) exampleClass

    采用逻辑值的属性可以在没有显式值的情况下使用。在前面的示例中,在没有显式值的情况下指定 Abstract 会将属性设置为 true。有关详细信息,请参阅类属性

  • ClassName - 有效的类名称以字母字符开头,并且可以包含字母、数字或下划线。将您的类保存在与类同名的文件中,文件扩展名为 .m

  • SuperclassName1 & SuperclassName2 & ... - 由 & 字符分隔的超类列表。有关从其他类派生类的详细信息,请参阅子类定义

classdef 模块可以包括以下类成员模块中的一个或多个:

  • 属性 - properties (Attributes) ... end 定义属性块。类定义可以包含多个属性块,每个块指定不同的特性设置,这些设置适用于该特定块中的属性。有关属性语法的详细信息,请参阅属性语法

  • 方法 - methods (Attributes) ... end 定义方法块。类定义可以包含多个方法块,每个块指定不同的属性设置,这些设置适用于该特定块中的方法。有关方法语法的详细信息,请参阅方法语法

  • 事件 - events (Attributes) ... end 定义事件块。类定义可以包含多个事件块,每个块指定不同的属性设置,这些设置适用于该特定块中的事件。有关事件语法的详细信息,请参阅事件和侦听程序语法

  • 枚举 - enumeration ... end 定义枚举块。有关定义枚举类的详细信息,请参阅定义枚举类

示例

全部折叠

Motor 类存储电机的当前速度,并提供启动和停止电机的基本功能。该类继承自 ElectricVehicleComponent 超类,并包括属性块和方法块。

classdef Motor < ElectricVehicleComponent
   
    properties
        CurrentSpeed = 0
        SpeedRange = [0, 180]
    end

    methods
        function motor = start(motor,speed)
            arguments
                motor (1,1) Motor
                speed (1,1) {mustBeReal, mustBeNonnegative}
            end
            if motor.CurrentSpeed > 0
                error("Motor:start:MotorAlreadyRunning",...
                    "Cannot start a motor that is already running.")
            end
            motor.CurrentSpeed = speed;   
        end
        
        function motor = stop(motor)
            if motor.CurrentSpeed == 0
                error("Motor:start:MotorNotRunning",...
                    "Cannot stop a motor that is not running.")
            end
            motor.CurrentSpeed = 0;
        end
    end
end

提示

  • 仅空白行和注释可以位于 classdef 的前面。

  • 类定义文件可以位于 MATLAB® 路径上的文件夹中,也可以位于父文件夹在 MATLAB 路径上的类文件夹中。类文件夹名称以 @ 字符开始,后跟类名称(例如 @MyClass)。有关类文件夹的详细信息,请参阅包含类定义的文件夹

  • propertiesmethodseventsenumeration 也是 MATLAB 函数的名称,这些函数用于查询给定对象或类名称的各个类成员。

  • 属性不能与其定义类同名。

  • 您可以在主类文件以外的文件中定义方法。有关详细信息,请参阅在单独文件中定义方法

版本历史记录

在 R2008a 中推出