我已经习惯了C#和Matlab,我正在尝试使用Eigen template library for linear algebra做一个简单的C ++程序。
很抱歉,我在基础知识方面苦苦挣扎:
示例代码(它不是编译,C#开发人员在这里痛苦):
struct MyStruct
{
Matrix3d* K1; //Is that the right way, using pointers?
Matrix3d* K2;
};
int main()
{
//Case 1
MyStruct* A = new MyStruct();
A->K1 = &(Matrix3d)Matrix3d::Random();
MyStruct* result = MyMethod(A);
//Case 2 - I noticed that everybody uses case 1, what is the difference?
MyStruct B;
B.K1 = &(Matrix3d)Matrix3d::Random();
B.K1(0,0) = 1; // Not working. How can I access it?
MyStruct* result = MyMethod(&B);
}
*MyStruct DoSomething(MyStruct& input)
{
MyStruct result;
result.K1 = ...
return &result;
}
答案 0 :(得分:0)
不熟悉Eigen。但我可以给你一些关于用C ++编程的一般建议。
- 在结构
中存储Matrix3d Eigen
如果需要分配Matrix3d对象,我建议在结构或类的构造函数和析构函数中进行资源管理。
还尝试使用 智能指针 的C类型指针。
参考:RAII。
- 将参数作为参数传递给方法
通常更喜欢通过引用传递(如果可以的话,可以使用const引用)。
- 返回包含Eigen对象引用的结构。
返回值确实取决于。如果只修改输入引用,则可能不需要返回值,或者如果MyStruct对象很小,则可以按值返回。
总之,正如评论所说,你需要C ++中资源管理的基本思想和实现方式。您可能希望找到一些书籍并学习这些主题。