Calling subclass functions to manipulate inputs for superclass constructor?
4 次查看(过去 30 天)
显示 更早的评论
I have a user-created subclass Domain2d < fegeometry. The fegeometry class is a default class in MATLAB, and the inputs for the fegeometry constructor are not user-friendly. Part of the idea of the Domain2d subclass is that its constructor should take user-friendly inputs, translate them into the complex inputs needed for the fegeometry constructor, then call the fegeometry constructor. The way the code is currently written, the task of manipulating the simple inputs into complex inputs is like:
classdef Domain2d < fegeometry
properties
end
methods
function self = Domain2d(simple_inputs)
% manipulate simple_inputs to complex_inputs
...(code here)
% call superclass constructor
self@fegeometry(complex_inputs);
end
end
end
This is kludge-y, but it works, and substantial code has been written that uses the bar object. But now I have a good reason to want to rewrite the bar object like
classdef Domain2d < fegeometry
properties
end
methods
function self = Domain2d(simple_inputs)
complex_inputs = translateSimpleToComplex(self,simple_inputs);
self@fegeometry(complex_inputs);
end
function complex_inputs = translateSimpleToComplex(self,simple_inputs)
...
end
end
end
The above produces the error "Calling the superclass constructor 'fegeometry' after an object use or after a return statement is not supported."
How should I proceed?
2 个评论
Matt J
2024-6-27
编辑:Matt J
2024-6-27
The handle class is a default class in MATLAB, and the inputs for the handle constructor are not user-friendly
Does the handle class constructor even accept inputs? What documentation are you getting this from? I've never heard of anyone explicitly calling the handle superclass constructor.
采纳的回答
Steven Lord
2024-6-27
I have a user-created subclass bar < handle.
Looking at the body of your constructor:
function self = bar(simple_inputs)
complex_inputs = translateSimpleToComplex(self,simple_inputs);
self@handle(complex_inputs);
end
the error message is correct. You cannot use self as an input to the translateSimpleToComplex function and then afterwards try to call the superclass constructor to create/initialize the variable self.
Why are you passing self as an input into translateSimpleToComplex? Is it simply so you can call the method and you're not actually trying to call methods or access properties of your class? If so turn it from an instance method (one that requires an instance of the class as input) into a Static method and call it using the name of your class, mybar.translateSimpleToComplex(simple_inputs) if you rename your class to mybar as an example.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Subclass Definition 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!