15-1 ?件導?程?設?

ɦV{]p]Object Oriented ProgrammingA² OOP^Oثen]pyA@밪{y䴩 OOP AҦp C++BJavaScriptBC#BJava AMATLAB]ҥ~A]N MATLAB b OOP Ug覡AHK²Ƴn骺HB{XiŪʻPƨϥΩʡAn骺޲z[²zC

Aڭ̭nإߤ@O]Class^AøgѦOغcXڪ]Object^Ap~iӨϥΪ󪺦UؤkӹFε{̫تCOO@ӵAҦpuHviHݦO@OA]tUةʽ誺wq]ҦpWrBʧOBB魫^AOhOڥOͪAҦpuդlvάOuZvNOѡuHvҲͪAN|TWrBʧOBB魫ʽC

HUڭ̱NHhdҡAӻ MATLAB p@ OOP 򥻷CMATLAB إO覡Oͤ@ӥHu@v}YƧAҦPO禡bƧUAҦpAbdҵ{ؿAAiHoı@ӥؿW٬O @polynomAoNOhOؿAҦ禡]]NO󪺤k^]boӥؿUC

Hint
AN]t @polynom Whؿ[ MATLAB jM|A~iHbNBϥλP polynom ΤkC

ۧڭ̭nwqغc禡]Constructor^HKͦhAغc禡W٥MOؿW٤@ˡ]]t @^AHhӨAغc禡WٴNO polynom.mA䤺epUG

Example 1: 15-ɦV{]p/@polynom/polynom.mfunction poly = polynom(vec) %POLYNOM Polynomial class constructor % poly = POLYNOM(vec) creates a polynomial object from the given vector vec % which contains the coefficients of the descending-order polynomial. if isa(vec, 'polynom') % Y vec wgO polynom Ah]wX poly = vec; else poly.c = vec(:).'; % NVq]w poly Y poly = class(poly, 'polynom'); % N poly [ polynom end

qWz{XiHݥXG

pGJO@ӦVqAoNOhYơ]ƦC^Aڭ̱NYƳ]w poly.cA̫ϥ class 禡N poly ܼƥ[ polynom C

pGJ vec wgO@ polynom AhXC]isa(vec, polynom) Ψˬd vec O_O@ polynom C^

ѤWz{X]iHݥXApoly ӬO@ӵcܼơA㦳@ c xshYơAO@g poly = class(poly, polynom) ӱN[󤧫Aڭ̦b~õLkg poly Өo c ȡAӥwqLkӨoơ]Ԩz^Ao]O OOP 򥻺믫GҦ󪺩ʽOLkN}񵹥~ҡAӥgѻPSw禡ӨoC

Fغc禡Aڭ̴NiHغc@ӦhAFuaiܦ󪺤eAڭ̥iHg@ܨ禡 display.m ܦhAܨ禡W٥Tw display.mAB @polynom ؿUA@ MATLAB ݭnܦhAY|۰ʩIs禡A䤺epUG

Example 2: 15-ɦV{]p/@polynom/display.mfunction display(poly) % POLYNOM/DISPLAY Display of a polynom disp(' '); disp([inputname(1),' = ']) disp(' '); disp([' ', polyAsString(poly)]) disp(' ');

Wz禡IsFt@Ө禡 polyAsString.mA\ONhରrΦAK[ݡA{XpUG

Example 3: 15-ɦV{]p/@polynom/polyAsString.mfunction s = polyAsString(poly) % POLYNOM/POLYASSTRING String representation of a polynom degree=length(poly.c)-1; s = sprintf('%d*x^%d', poly.c(1), degree); for i=degree-1:-1:0 coef = poly.c(degree-i+1); if coef >=0 s=sprintf('%s + %d*x^%d', s, coef, i); else s=sprintf('%s - %d*x^%d', s, -coef, i); end end

@Fغc禡 polynom.m Mܨ禡 display.m Aڭ̴NiHͤ@ӦhܦApUG

Example 4: 15-ɦV{]p/test01.mp = polynom([3 4 2 1]) p = 3*x^3 + 4*x^2 + 2*x^1 + 1*x^0

b MATLAB ROҲͪrAYOܨ禡 display.m ҲͪGC]MAoӦriणOܲŦX@hgkAŪ̥iHۦק display.mAϨ䲣ͪr}G@ǡC^

Hint
Wzܨ禡ݩ@몫󪺤ܨ禡A䥦P禡٦[BBB򥻹B⤸AШU@`C

ѨϥΪ̩ҩwqOAƹWOݩ MATLAB Oh@AMATLABOhpUG

䤤 user classes NOѨϥΪ̩wqOA~ӤF structure OSʡCѤWzOhAڭ̥iHAѸOqYC

@ӨA䴩 OOP {yjUz򥻥\G

  1. 禡ιB⤸ (Function and operator overloading)GھگSwOΪAAiHͦUؤkCoǤk禡W٥iHM MATLABب禡@ˡAMATLAB|ھڿJѼƪƫAAӨMwIs@ب禡C
  2. ƩMkʸ (Encapsulation of data and methods)GҦ󪺩ʽAõLkq~ɪoέקAgѦҴѪkA~oέק惡󪺩ʽCo˥iHOҪ󪺧ʡA|~DŪέקC~A󪺤k]uAΩ󪫥󥻨ATO|~ΡC
  3. ~ (Inheritance)GOiH~YAҦpuHvO@OAӡuǥ͡vhOuHvlOA]uǥ͡vOiH~ӡuHvOʽMkC~ӡAiڭ̹u@ɪyz[C
  4. EX (Aggregation)Gڭ̥iHϥλEXөwqYOAgѳoOҲͪAiH]tLCҦpAuǥ͡vҭתuҵ{vANiHѻEXөwqC

HUX`N MATLAB o OOP Sʪ@MdҡC


MATLAB{]pGig