从C++中的对象中获取数组

Get array from object in c++

这个问题可能很简单,但我从不在 C++ 中使用原始指针或数组,所以...

我需要使用如下所示的库函数:

void f(double a[3][3], double b[3], double c[3]);

ab用于输入,结果存储在c中。

a的计算有点复杂,但不会改变,所以只计算一次并保存结果是有意义的。在我的程序中,我可以将它 link 转换为 X 类型的对象。

class X{
public:
X(){ 
    a = {{1,2,3},
         {4,5,6},
         {7,8,9}}; 
    }

private:
    double a[3][3];
}

如何为 X::a 写一个 getter 可以在函数 f 中使用?

我想这样调用函数 f:

#include "X.h"

int main(int argc, char *argv[]){

    X o = X(); //create object
    double a[3][3] = o.getA(); // I want to get a somehow
    double b[3] =  {1,2,3}; // create dummy b
    double c[3] = {}; // create empty c
    f(a,b,c); // call funktion to populate c
    for(int i=0; i<3; ++i){
        std::cout << c[i] << endl;
    }
}

你知道 std::vector 是 C++ 中二维数组的方法,但如果你不能绕过你面临的障碍,那么可以将矩阵作为参数传递给getter 函数,像这样:

#include <iostream>

class X {
 public:
    void getA(double (&array)[3][3]) {
        for (int i = 0; i < 3; ++i)
            for (int j = 0; j < 3; ++j)
                array[i][j] = a[i][j];
    }
 private:
    double a[3][3] = {{1,2,3},
            {4,5,6},
            {7,8,9}};
};

int main(void) {
    X o = X();
    double a[3][3];
    o.getA(a);
    for(int i = 0; i < 3; ++i)
        for(int j = 0; j < 3; ++j)
            std::cout << a[i][j] << std::endl;
    return 0;
}

此代码段应该符合您的目的。

#include <iostream>
#include <string>

using namespace std;

class X {
public:
    X() {
    }

    typedef double (*ptr_matrix)[3];

    ptr_matrix getA(){
        return a;
    }

private:
    double a[3][3] = {{ 1,2,3},
        {4,5,6},
        {7,8,9}};
};

void f(double a[3][3], double b[3], double c[3])
{
    cout<<"Inside f function";
    for(auto i = 0; i < 3;i++) {
        cout<<endl;
        for(auto j = 0 ; j < 3;j++)
            cout<<a[i][j];
    }
}

int main()
{
    X o = X(); //create object
    double (*a)[3] = NULL;
    a = o.getA(); // I want to get a somehow

    double b[3] = {0};
    double c[3] = {0};

    f(a,b,c);

}