面向对象编程 #

一、类定义基础 #

1.1 基本类定义 #

matlab
% 保存为 Person.m
classdef Person
    properties
        name
        age
    end
    
    methods
        function obj = Person(name, age)
            obj.name = name;
            obj.age = age;
        end
        
        function displayInfo(obj)
            fprintf('姓名: %s, 年龄: %d\n', obj.name, obj.age);
        end
    end
end

% 使用
p = Person('张三', 25);
p.displayInfo();

1.2 属性定义 #

matlab
classdef Student
    properties
        name                    % 公有属性
    end
    
    properties (Access = private)
        id                      % 私有属性
    end
    
    properties (Access = protected)
        scores                  % 保护属性
    end
    
    properties (Constant)
        MAX_SCORE = 100         % 常量属性
    end
    
    properties (Dependent)
        average                 % 依赖属性
    end
    
    methods
        function obj = Student(name, id)
            obj.name = name;
            obj.id = id;
            obj.scores = [];
        end
        
        function avg = get.average(obj)
            if isempty(obj.scores)
                avg = 0;
            else
                avg = mean(obj.scores);
            end
        end
        
        function obj = set.scores(obj, values)
            if any(values > obj.MAX_SCORE)
                error('分数不能超过最大值');
            end
            obj.scores = values;
        end
    end
end

1.3 方法定义 #

matlab
classdef Calculator
    properties
        result
    end
    
    methods
        % 构造函数
        function obj = Calculator()
            obj.result = 0;
        end
        
        % 普通方法
        function obj = add(obj, value)
            obj.result = obj.result + value;
        end
        
        function obj = subtract(obj, value)
            obj.result = obj.result - value;
        end
        
        function reset(obj)
            obj.result = 0;
        end
    end
    
    methods (Static)
        % 静态方法
        function result = multiply(a, b)
            result = a * b;
        end
    end
end

% 使用
calc = Calculator();
calc = calc.add(10);
calc = calc.subtract(3);
disp(calc.result);  % 7

% 调用静态方法
result = Calculator.multiply(3, 4);  % 12

二、构造函数 #

2.1 基本构造函数 #

matlab
classdef Rectangle
    properties
        width
        height
    end
    
    methods
        function obj = Rectangle(w, h)
            if nargin == 0
                w = 1;
                h = 1;
            end
            obj.width = w;
            obj.height = h;
        end
        
        function area = getArea(obj)
            area = obj.width * obj.height;
        end
    end
end

% 使用
r1 = Rectangle();      % 默认值
r2 = Rectangle(3, 4);  % 指定值

2.2 重载构造函数 #

matlab
classdef Point
    properties
        x
        y
    end
    
    methods
        function obj = Point(varargin)
            switch nargin
                case 0
                    obj.x = 0;
                    obj.y = 0;
                case 1
                    obj.x = varargin{1};
                    obj.y = 0;
                case 2
                    obj.x = varargin{1};
                    obj.y = varargin{2};
            end
        end
    end
end

三、继承 #

3.1 基本继承 #

matlab
% 父类 Animal.m
classdef Animal
    properties
        name
    end
    
    methods
        function obj = Animal(name)
            obj.name = name;
        end
        
        function speak(obj)
            disp('动物发出声音');
        end
    end
end

% 子类 Dog.m
classdef Dog < Animal
    methods
        function obj = Dog(name)
            obj@Animal(name);  % 调用父类构造函数
        end
        
        function speak(obj)
            disp([obj.name ' 汪汪叫']);
        end
    end
end

% 使用
dog = Dog('小黄');
dog.speak();  % 小黄 汪汪叫

3.2 多重继承 #

matlab
classdef Flying
    methods
        function fly(obj)
            disp('飞行中...');
        end
    end
end

classdef Swimming
    methods
        function swim(obj)
            disp('游泳中...');
        end
    end
end

classdef Duck < Animal & Flying & Swimming
    methods
        function obj = Duck(name)
            obj@Animal(name);
        end
    end
end

% 使用
duck = Duck('唐老鸭');
duck.speak();  % 动物发出声音
duck.fly();    % 飞行中...
duck.swim();   % 游泳中...

四、方法重载 #

4.1 运算符重载 #

matlab
classdef Vector2D
    properties
        x
        y
    end
    
    methods
        function obj = Vector2D(x, y)
            obj.x = x;
            obj.y = y;
        end
        
        % 加法运算符
        function result = plus(obj1, obj2)
            result = Vector2D(obj1.x + obj2.x, obj1.y + obj2.y);
        end
        
        % 减法运算符
        function result = minus(obj1, obj2)
            result = Vector2D(obj1.x - obj2.x, obj1.y - obj2.y);
        end
        
        % 乘法运算符(标量乘法)
        function result = mtimes(obj, scalar)
            result = Vector2D(obj.x * scalar, obj.y * scalar);
        end
        
        % 显示
        function display(obj)
            fprintf('Vector2D(%.2f, %.2f)\n', obj.x, obj.y);
        end
    end
end

% 使用
v1 = Vector2D(1, 2);
v2 = Vector2D(3, 4);
v3 = v1 + v2;   % Vector2D(4.00, 6.00)
v4 = v1 * 2;    % Vector2D(2.00, 4.00)

4.2 索引重载 #

matlab
classdef MyArray
    properties
        data
    end
    
    methods
        function obj = MyArray(data)
            obj.data = data;
        end
        
        % 圆括号索引
        function result = subsref(obj, s)
            switch s(1).type
                case '()'
                    result = obj.data(s(1).subs{:});
                case '.'
                    result = builtin('subsref', obj, s);
            end
        end
        
        % 圆括号赋值
        function obj = subsasgn(obj, s, value)
            switch s(1).type
                case '()'
                    obj.data(s(1).subs{:}) = value;
            end
        end
    end
end

五、句柄类 #

5.1 值类 vs 句柄类 #

matlab
% 值类(默认)
classdef ValueClass
    properties
        value
    end
    methods
        function obj = ValueClass(v)
            obj.value = v;
        end
    end
end

% 句柄类
classdef HandleClass < handle
    properties
        value
    end
    methods
        function obj = HandleClass(v)
            obj.value = v;
        end
    end
end

% 区别
v1 = ValueClass(10);
v2 = v1;
v2.value = 20;
disp(v1.value);  % 10(值类:复制)

h1 = HandleClass(10);
h2 = h1;
h2.value = 20;
disp(h1.value);  % 20(句柄类:引用)

5.2 句柄类方法 #

matlab
classdef Counter < handle
    properties
        count
    end
    
    methods
        function obj = Counter()
            obj.count = 0;
        end
        
        function increment(obj)
            obj.count = obj.count + 1;
        end
        
        function reset(obj)
            obj.count = 0;
        end
    end
end

% 使用
counter = Counter();
counter.increment();
counter.increment();
disp(counter.count);  % 2

六、事件 #

6.1 定义事件 #

matlab
classdef TemperatureSensor < handle
    properties
        temperature
    end
    
    events
        temperatureChanged
    end
    
    methods
        function obj = TemperatureSensor()
            obj.temperature = 20;
        end
        
        function setTemperature(obj, newTemp)
            obj.temperature = newTemp;
            notify(obj, 'temperatureChanged');
        end
    end
end

6.2 监听事件 #

matlab
% 创建传感器
sensor = TemperatureSensor();

% 添加监听器
listener = addlistener(sensor, 'temperatureChanged', ...
    @(src, evt) disp(['温度变化: ' num2str(src.temperature) '°C']));

% 触发事件
sensor.setTemperature(25);  % 显示: 温度变化: 25°C

% 删除监听器
delete(listener);

七、实用示例 #

7.1 链表类 #

matlab
classdef ListNode < handle
    properties
        data
        next
    end
    
    methods
        function obj = ListNode(data)
            obj.data = data;
            obj.next = [];
        end
        
        function obj = append(obj, data)
            if isempty(obj.next)
                obj.next = ListNode(data);
            else
                obj.next = obj.next.append(data);
            end
        end
        
        function display(obj)
            node = obj;
            while ~isempty(node)
                fprintf('%d -> ', node.data);
                node = node.next;
            end
            fprintf('nil\n');
        end
    end
end

7.2 单例模式 #

matlab
classdef Singleton < handle
    properties (Access = private)
        data
    end
    
    properties (Constant)
        instance = Singleton();
    end
    
    methods (Access = private)
        function obj = Singleton()
            obj.data = [];
        end
    end
    
    methods
        function setData(obj, value)
            obj.data = value;
        end
        
        function result = getData(obj)
            result = obj.data;
        end
    end
end

% 使用
s1 = Singleton.instance;
s1.setData(100);
s2 = Singleton.instance;
disp(s2.getData());  % 100(同一个实例)

八、总结 #

本章学习了:

  1. 类定义:classdef、properties、methods
  2. 构造函数:初始化对象
  3. 继承:单继承、多重继承
  4. 方法重载:运算符、索引
  5. 句柄类:引用语义
  6. 事件:发布-订阅模式

下一章将学习错误处理。

最后更新:2026-03-27