2

Matlab では、クラスのプライベート メンバーに対していくつかの操作を実行したいと考えています。他のクラスでもこれとまったく同じタスクを実行したいと思います。明らかな解決策は、このタスクを実行するためにすべてのクラスが呼び出す別の M ファイルに関数を記述することです。ただし、Matlab では不可能のようです (以下を参照)。これを達成する別の方法はありますか?

具体的な問題は次のとおりです。内容を含む m ファイルが 1 つあるとします。

classdef PrivateTest
    properties (Access=private)
        a
    end

    methods
        function this = directWrite(this, v)
            this.a = v;
        end
        function this = sameFileWrite(this, v)
            this = writePrivate(this, v);
        end
        function this = otherFileWrite(this, v)
            this = otherFileWritePrivate(this, v);
        end
        function print(this)
            disp(this.a);
        end
    end
end

function this = writePrivate(this, v)
    this.a = v;
end

...そして、内容を含む別の m ファイル

function this = otherFileWritePrivate(this, v)
    this.a = v;
end

をインスタンス化した後p = PrivateTest、これらのコマンドは両方とも正常に機能します (予想どおり)。

p = p.directWrite(1);
p = p.sameFileWrite(2);

...しかし、このコマンドは同じコードであっても機能しません.mファイルが異なるだけです:

p = p.otherFileWrite(3);

したがって、クラスのプライベート プロパティに対して操作を実行するコードは、それらのプライベート プロパティを定義する classdef と同じ m ファイルにある必要があるようです。別の可能性として、すべてのクラスが書き込みメソッドを持つクラスを継承するようにすることも考えられますが、Matlab ではこれも許可されていません。1 つの m ファイルには、次のコードがあります。

classdef WriteableA
    methods
        function this = inheritWrite(this, v)
            this.a = v;
        end
    end
end

...そして別の m ファイルには、次のコードがあります。

classdef PrivateTestInherit < WriteableA
    properties (Access=private)
        a
    end
end

ただし、 をインスタンス化した後p = PrivateTestInherit;、このコマンドp.inheritWrite(4)は前と同じエラー メッセージを表示します。「'PrivateTestInherit' クラスの 'a' プロパティの設定は許可されていません。」

これに照らして、Matlab でプライベート プロパティを操作するコードを一般化することはどのように可能ですか、または可能ですか?

4

1 に答える 1

0

クラスの外部でプライベート プロパティを操作することはできないため、プライベートと呼ばれます。この考え方はカプセル化と呼ばれます。

あなたは多くの方法でそれを解決することができます:

  1. private をラップする public プロパティを定義し、変更します。(以下のコードを参照)
  2. (継承パターン) 共通の親クラスを行い、他のクラスは関数を継承する

classdef PrivateTest
    properties (Access=private)
        a
    end

    properties(Access=public,Dependent)
        A
    end

    methods
        function this = set.A(this,val)
            this.a = val;
        end

        function val = get.A(this)
           val = this.a;
        end

        function this = directWrite(this, v)
            this.a = v;
        end
        function this = sameFileWrite(this, v)
            this = writePrivate(this, v);
        end
        function this = otherFileWrite(this, v)
            this = otherFileWritePrivate(this, v);
        end
        function print(this)
            disp(this.a);
        end
    end
end

function this = writePrivate(this, v)
    this.A = v;
end
于 2012-10-10T19:35:53.573 に答える