MATLAB CLASSES的getter和setter方法 [英] MATLAB CLASSES getter and setters

查看:117
本文介绍了MATLAB CLASSES的getter和setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Java背景.我在Matlab中的类(尤其是getter和setter)上遇到问题.收到一条消息,说句柄和值类之间存在冲突,我对执行该操作有些迷茫,因此如果缺少更好的用词,任何帮助都会有所帮助.

I come from a Java background. I am having issues with classes in Matlab particularly getters and setters. getting a message saying conflict between handle and value class I'm a little lost with what to do so any help for lack of a better word will be helpful.

classdef Person
properties(Access = private)
    name;
    age; 
end


methods
    % class constructor
    function obj = Person(age,name)         
             obj.age = age;
             obj.name = name;
    end

    %getters
    function name = get.name(obj)          
    end

    function age = get.age(obj)
    end

    %setters
    function value = set.name(obj,name)
    end

    function value = set.age(obj,age)
    end

end

结束

推荐答案

实施

由于您的类当前是默认Value类的子类,因此您的设置者需要返回修改后的对象:

Implementation

Since your class is currently a subclass of the default Value class, your setters need to return the modified object:

function obj = set.name(obj,name)
end
function obj = set.age(obj,age)
end

来自该文档:如果将[值类]传递给函数,则该函数必须返回修改后的对象."并且特别是:在值类中,修改对象的方法...必须返回修改后的对象,以将其复制到现有对象变量上."

From the documention: "If you pass [a value class] to a function, the function must return the modified object." And in particular: "In value classes, methods ... that modify the object must return a modified object to copy over the existing object variable".


句柄类(classdef Person < handle)不需要返回修改后的对象(例如返回void):


Handle classes (classdef Person < handle) do not need to return the modified object (like returning void):

function [] = set.name(obj,name)
end
function [] = set.age(obj,age)
end

值与句柄

再深入一点,Value类和Handle类之间的区别主要在于赋值:

Value vs. Handle

Going a bit deeper, the difference between a Value class and a Handle class lies mostly in assignment:

  • 将Value类实例分配给变量会创建该类的副本.
  • 将Handle类实例分配给变量会创建对该实例的引用(别名).

Mathworks具有关于此主题的摘要. 为了解释他们的说明,Value类的行为是

The Mathworks has a good rundown on this topic. To paraphrase their illustration, the behavior of a Value class is

% p  is an instance of Polynomial
p = Polynomial(); 
% p2 is also an instance of Polynomial with p's state at assignment
p2 = p;

并且Handle类是

% db is an instance of Database
db = Database();
% db2 is a reference to the db instance
db2 = db;

这篇关于MATLAB CLASSES的getter和setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆