When constructing an instance of class, the constructor must preserve the class of the returned object.

13 visualizaciones (últimos 30 días)
I'm currently working on a project, I've never worked with OOD in Matlab before and it seems really overwhelming. When compiling the code with main file it gives error statating "When constructing an instance of class 'cSubstance', the constructor must preserve the class of the returned object."
classdef cSubstance
properties
varargin
end
methods
function this = cSubstance(varargin)
this = struct( ...
'mName', [],... %Name
'mMW', [],... %Molecular weight (g/mol)
'mTc', [],... %Critical temperature (K)
'mPc', [],... %Critical pressure (Pa)
'mw', [],... %Acentric factor
'mAntA', [],... %Parameter A of Antoine equation, lnP(Pa) = A-B/(T(K)+C)
'mAntB', [],... %Parameter B of Antoine equation, lnP(Pa) = A-B/(T(K)+C)
'mAntC', [],... %Parameter C of Antoine equation, lnP(Pa) = A-B/(T(K)+C)
'mTf', [],... %Melting temperature at the triple point (K)
'mHf', [],... %Melting enthalpy at the triple point (J/mol)
'mEoSParam', []); %EoS-specific parameter(s)
%Initialize parameters
this.mName = ' ';
this.mMW = 0;
this.mTc = 0;
this.mPc = 0;
this.mw = 0;
this.mAntA = 0;
this.mAntB = 0;
this.mAntC = 0;
this.mTf = 0;
this.mHf = 0;
this.mEoSParam = {};
if nargin > 0, this.mName = varargin{1}; end
if nargin > 1, this.mMW = varargin{2}; end
if nargin > 2, this.mTc = varargin{3}; end
if nargin > 3, this.mPc = varargin{4}; end
if nargin > 4, this.mw = varargin{4}; end
if nargin > 5, this.mAntA = varargin{5}; end
if nargin > 6, this.mAntB = varargin{6}; end
if nargin > 7, this.mAntC = varargin{7}; end
if nargin > 8, this.mTf = varargin{8}; end
if nargin > 9, this.mHf = varargin{9}; end
if nargin > 10, this.mEoSParam = varargin{10}; end
end
end
end

Respuestas (1)

per isakson
per isakson el 24 de Jun. de 2021
Editada: per isakson el 24 de Jun. de 2021
I don't know C++. (For some reason you added the tag "C++".) I guess you are biased by some other language. You need to look closer at some Matlab documentation on OO.
I modified your class definition (see attached). Now creating an instance works.
cs = cSubstance('test')
cs =
cSubstance with properties: mName: 'test' mMW: 0 mTc: 0 mPc: 0 mw: 0 mAntA: 0 mAntB: 0 mAntC: 0 mTf: 0 mHf: 0 mEoSParam: {}

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by