将 2D 数组传递给另一个类C++
passing 2D array to another class C++
我正在尝试计算矩形的周长。 首先,我将提示用户 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。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 如何将指针从一个void函数传递到另一个C++
- 如何从另一个文件继承私有成员变量和公共函数
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- C++-我可以创建另一个类的成员并在构造函数中使用它吗
- 如何在C++中将函数发送到另一个进程
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口