필터 지우기
필터 지우기

MATLAB coder: use constructor instead of init method

조회 수: 4 (최근 30일)
Brandon
Brandon 2023년 11월 17일
댓글: PK 2024년 2월 28일
Using MATLAB Coder (C++), both of these classes:
classdef A
properties
x = 1;
end
end
classdef A
methods
function obj = A()
obj.x = 1;
end
end
end
result in a class A with an empty default ctor, and and init method (that sets x=1), where, clearly(?) the intent is to default construct with x=1 (and not split initialization and construction)
Can I disable the generation of the init method in general? That seems IMO like programming C-style with C++ classes as a little bit of syntaxtic sugar.

답변 (1개)

Varun
Varun 2023년 11월 28일
Hi Brandon,
I understand that you do not want “init” method explicitly to initialize the properties rather there should be a default constructor that does this initialization.
MATLAB Coder often generates “init” function for properties even if they are set in the constructor in MATLAB. This is the default behaviour of MATLAB Coder while converting a MATLAB class into C++ class. However, you can manually modify the generated C++ code to initialize properties directly in the constructor, aligning it with typical C++ class behavior.
Please follow below steps:
  1. Open the generated C++ files (".cpp" and ".h") and locate the constructor ("A::A"). Adjust the constructor to initialize the properties directly:
// A.cpp
#include "A.h"
// Constructor
A::A()
{
// Initialize properties directly
x = 1;
}
2. Recompile the modified C++ code using your preferred C++ compiler. Since you have modified the generated code, and you should carefully review and test the modified code to ensure correctness.
Please refer to the following documentation to learn more about generating C++ classes from MATLAB classes:
Hope this helps.
  댓글 수: 2
Brandon
Brandon 2023년 11월 28일
Not interested in modifying generated code; that's not really sustainable in CI.
Mathworks documentation indicates that this init method is just how things get done. Looks like if I want a more modern styled class I'll have to wrap the generated code.
PK
PK 2024년 2월 28일
Is this still the accepted answer? The generated C++ code does not seem to follow modern C++ coding guidelines. I feel like a much better solution is simply not to use the code generator due to the poor quality of code that is generated. Is anyone working on actually generating modern, efficient C++ code?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 MATLAB Coder에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by