在MatLab中,我有一个超类A,它接受一些参数,x和y
classdef A < handle
properties
x;
y;
z;
end
methods
function this = A(x, y)
this.x = x;
this.y = y;
this.initialize();
end
function initialize(this)
this.z = this.x + this.y;
end
end
end
初始化方法应该做一些初始计算,以便以后加紧计算。
现在我想创建A的子类B,它有自己的初始化,但B应该在A之前初始化。
classdef B < A
properties
p
end
methods
% B takes another parameter p
function this = B(p)
% Since B is a subclass of A, and A takes some parameters we have to
% call the constructer of A as the first thing.
this = this@A([], []);
this.p = p;
end
function initialize(this)
this.x = this.p(1);
this.y = this.p(2);
% This is when initialize of A should be called.
end
end
end
基本上我只是想在A之前初始化B,但因为必须首先调用父的构造函数,所以我无法弄清楚如何做到这一点。
在PHP中我会做这样的事情
class A {
public function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
$this->initialize();
}
public function initialize() {
$this->z = $this->x + $this->y;
}
}
class B extends A {
public function __construct($p) {
// Does not call the parent constructor.
$this->p = $p;
$this->initialize();
}
public function initialize() {
$this->x = $this->p[0];
$this->y = $this->p[1];
parent::initialize(); // Now we are ready to initialize A
}
}
有没有一种聪明的方法来设计我想要的MatLab?我是否必须放弃B类中A的继承?
答案 0 :(得分:2)
这违反了OOP的原则。您要实现的目标基本上排除了B
应该来自A
。据我所知,你真的想要重载A
的构造函数。要么使用nargin
A
进行检查,要么出于某种原因确实想要B
,只需在{{1}的构造函数中使用:this = this@A(p(1), p(2);
相反,要正确调用B
的构造函数(并删除属性A
)。
这是使用p
模拟重载构造函数的方法:
nargin
通过正确调用classdef A < handle
properties
x;
y;
z;
end
methods
function this = A(x, y)
if nargin==1 % 'p' was passed as 'x'
this.x = x(1);
this.y = x(2);
else
this.x = x;
this.y = y;
end
this.initialize();
end
function initialize(this)
this.z = this.x + this.y;
end
end
end
的构造函数,您可以从B
派生A
:
A
答案 1 :(得分:2)
因此出现了并发症:
如果创建子类对象,MATLAB®会调用超类构造函数来初始化子类对象的超类部分。默认情况下,MATLAB不带参数调用超类构造函数。 [src]
您可以通过将其工作包装在if
语句中来显式调用超类构造函数,该语句取决于传递的参数数量(nargin
):
function this = A(x, y)
if (nargin ~= 0) % or (nargin == 2) in this case
this.x = x;
this.y = y;
this.initialize();
end
end
然后B
的方法看起来像:
function this = B(p)
this.p = p;
this.initialize();
end
function initialize(this)
this.x = this.p(1);
this.y = this.p(2);
initialize@A(this);
end
帖子中可能只是错误,但A
的{{1}}方法引用了未定义的变量initialize
和x
,而不是它们的属性。它应该是:
y