MATLAB 面向对象编程(十一)成员方法共享Static和属性共享constant、persistent

  1. 类的成员方法
    静态成员方法(Static)也叫做类方法,在前面的loadobj方法中有涉及,它不需要具体的对象就可以调用。
classdef Base1 < handle
    properties
        x
    end
    methods
        function obj = Base1()
            disp('Base1');
        end
    end
    methods(Static)
        function foo()
            disp('Static function')
        end
    end
end

在命令行里面输入Base1.foo(),直接通过类名就可以调用,可以得到
在这里插入图片描述

同样也可以用对象来调用
在这里插入图片描述
可以发现静态方法和普通方法一个重要的不同就是,静态方法的输入参数中没有obj作为对象输入,同样这也说明了静态方法不能调用普通方法也不能访问属性,否则就没有必要定义为静态方法。

  1. 共享属性
    共享属性可以分为两类,一类是常量,一类是变量。、

常量: 对于常量可以通过Constant实现共享。

classdef Base1 
    properties (Constant)
        x = rand(100,100);
    end
    methods
        function obj = Base1()
            disp('Base1');
        end
    end
    methods(Static)
        function foo()
            disp('Static function')
        end
    end
end
classdef Base2 
    properties
        x = rand(100,100);   
    end
    methods
        function obj = Base2()
            disp('Base1');
        end
    end
    methods(Static)
        function foo()
            disp('Static function')
        end
    end
end

我们可以对比上面两种方法,
在这里插入图片描述
说明x并没有算入A的内存中,我们再声明一个Base1对象,观察x是否相同。
在这里插入图片描述
说明所有Base1对象共享相同的x属性。

变量: 变量共享可以使用persistent实现共享。

classdef Sub 
    properties 
       z
    end
    methods
        function obj = Sub()
             persistent count ;
             if isempty(count)
                 count = 1;
             else
                 count = count + 1;
             end
           count
        end
    end
end

在这里插入图片描述
可以看出count的值是跟随着增加的。

发布了50 篇原创文章 · 获赞 66 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43157190/article/details/104461584
今日推荐