2013-03-06 150 views
5

所以我在设置对象的特定属性时遇到了问题。我对Matlab比较陌生,特别是面向对象编程。下面是我的代码:在Matlab中设置对象的属性

classdef Card < handle 
properties 
    suit; 
    color; 
    number; 
end 

methods 
    %Card Constructor 
    function obj= Card(newSuit,newColor,newNumber) 
     if nargin==3 
     obj.suit=newSuit; 
     obj.color=newColor; 
     obj.number=newNumber; 
     end 
    end 

    function obj=set_suit(newSuit) 
     obj.suit=(newSuit); 
    end 

它都运行良好,直到我尝试set_suit函数。这是我在命令窗口中输入的内容。

a=Card 

a = 

Card handle 

Properties: 
    suit: [] 
color: [] 
number: [] 

Methods, Events, Superclasses 

a.set_suit('Spades') 
Error using Card/set_suit 
Too many input arguments. 

这总是返回太多输入参数的错误。一般来说,任何有关这种面向对象编程的帮助都将不胜感激。

回答

4

对于类methods(非static)第一个参数是对象本身。所以,你的方法应该是这样的:

function obj=set_suit(obj, newSuit) 
    obj.suit=(newSuit); 
end 

注意额外obj参数在参数列表的开头。

现在,你可以通过

a.set_suit('Spades'); 

set_suit(a, 'Spades'); 
+0

调用此方法,或者这工作完全!非常感谢! – 2013-03-06 06:43:35