starting with oop

1 次查看(过去 30 天)
Christof
Christof 2011-12-1
Hi, I just started playing with oop in Matlab. Dont have any other oop experience, so I seem to get lost in the first steps alerady. when I try to call teh following class
classdef myclass
%MYCLASS Summary of this class goes here
% Detailed explanation goes here
properties
t1
end
methods
function obj=myclass(arg1)
obj.t1=myclass.p(arg1);
end
end
methods (Static)
function p = pi(tol)
[n d]=rat(pi,tol);
p=n/d;
end
end
end
I always get the error
The class myclass has no property or method named 'p'.
How can I prevent that error?
Cheers

回答(1 个)

David Young
David Young 2011-12-1
You need to replace
obj.t1=myclass.p(arg1);
with
obj.t1=myclass.pi(arg1);
You're making the (I suspect quite common) mistake of using the output variable name from the function instead of the name of the function itself.
If you make that change, the constructor runs:
>> m = myclass(3)
m =
myclass
Properties:
t1: 3
Does that do what you expect now?
  2 个评论
Christof
Christof 2011-12-1
that was the mistake. thanks.
another question, though. if I define the method as a regular method, not as a static method, I cant call it from the constructor. is there a way to do?
David Young
David Young 2011-12-1
Yes, if pi is not static, you can do
obj.t1 = obj.pi(arg1);
By the way, it would be better to avoid "pi" as a method name, so that it can't be confused with the inbuilt function pi.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Scope Variables and Generate Names 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by