将 2D 数组传递给另一个类C++

passing 2D array to another class C++

本文关键字:另一个 C++ 2D 数组      更新时间:2023-10-16

我正在尝试计算矩形的周长。 首先,我将提示用户 4 次输入 X 和 Y 线并将其存储到 2D 数组中,然后将此 2D 数组传递给另一个类,即方法类以继续计算周长。但问题是,我不知道如何将 2d 数组传递给方法类。

我不是在问如何计算周长,我只需要知道如何将 2D 数组从主数组传递到方法类并在方法类处获取 2D 数组。请指教。

主.cpp

Method method;
int main() {
   int storeXandY[4][2];
       for(int i=1;i<5;i++)
       {
           cout << "Please enter x-ordinate" << i<< endl;
           cin>>storeXandY[i][0];
           cout << "Please enter y-ordinate" << i << endl;
           cin>>storeXandY[i][1];
       }
    //how to pass the 2D array to method class to do some calculations?
    // I was thinking something like passing the 2d array to a consturctor but don't know whether it can be done
       method.constructor(storeXandY);
 }

方法.h

   //not sure of what to do
public: 
    constructor() {
    }

方法.cpp

    //how to get the cords from 2d array from main

请指教。谢谢

你可以这样做:

class Method{
    ...
    public int calcPerimeter(int vals[4][2])
    {
       // do your calculation here using vals array
    }
    ...
}

从main(),你可以简单地做:

Method m = new Method();
int perimeter;
m.calcPerimeter(<your_array_name>);

由于您正在编写C++,因此应尽量避免使用 C 样式数组。我会这样做

Method method;
int main() {
   vector<vector<int> > storeXandY(4);
   for(int i=0; i!=4; ++i) storeXandY[i].resize(2);
   for(int i=1;i<5;i++)
   {
       cout << "Please enter x-ordinate" << i<< endl;
       cin>>storeXandY[i-1][0]; /* you need i-1 here, not i */
       cout << "Please enter y-ordinate" << i << endl;
       cin>>storeXandY[i-1][1];
   }
   method.calcPerimeter(storeXandY);
 }

其中method::calcPerimeter声明如下

your_return_type method::calcPerimeter(const vector<vector<int> >& rectangle);

使用向量的优点是,您可以通过调用它们的 size 成员函数来获取它们持有的元素数,因此在上面的代码中storeXandY.size()等于 4,storeXandY[0].size()等于 2。

相关文章: