如何处理C ++中的数组(堆栈上声明)? [英] How to deal with arrays (declared on the stack) in C++?

查看:165
本文介绍了如何处理C ++中的数组(堆栈上声明)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类来分析,保持了结果阵列成员矩阵:

I have a class to parse a matrix that keeps the result in an array member:

class Parser
{
  ...
  double matrix_[4][4];
};

这个类的用户需要调用API函数(如,一个功能我没有控制权,所以我不能只是改变它的界面使事情变得更加容易地工作),看起来像这样:

The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:

void api_func(const double matrix[4][4]);

我已经拿出呼叫者数组结果传递给函数的唯一方法是通过使成员public:

The only way I have come up with for the caller to pass the array result to the function is by making the member public:

void myfunc()
{
  Parser parser;
  ...
  api_func(parser.matrix_);
}

这是做事情的唯一途径?我对声明如下僵化的多维数组是如何震惊。我以为矩阵_ 将基本上是一样的双** ,我可以在两者之间投(安全)。事实证明,我甚至不能找到的不安全的方式,事物之间施放。假设我添加一个访问到解析器类:

Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought matrix_ would essentially be the same as a double** and I could cast (safely) between the two. As it turns out, I can't even find an unsafe way to cast between the things. Say I add an accessor to the Parser class:

void* Parser::getMatrix()
{
  return (void*)matrix_;
}

这将编译,但我不能使用它,因为似乎没有要投回怪人数组类型的方式:

This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type:

  // A smorgasbord of syntax errors...
  api_func((double[][])parser.getMatrix());
  api_func((double[4][4])parser.getMatrix());
  api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type

该错误是:

错误C2440:类型转换:无法从无效*转换为const的双重[4] [4]

error C2440: 'type cast' : cannot convert from 'void *' to 'const double [4][4]'

...有一个有趣的补遗:

...with an intriguing addendum:

有没有转换到数组类型,虽然有转换来引用或指针数组

There are no conversions to array types, although there are conversions to references or pointers to arrays

我不能确定如何转换为引用或指针数组要么,尽管这可能不会帮助我在这里。

I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here.

当然,在这一点上该事项纯学术,因为无效* 的演员是很难比单个类成员留下清洁的公共!

To be sure, at this point the matter is purely academic, as the void* casts are hardly cleaner than a single class member left public!

推荐答案

下面是一个不错的,干净的方式:

Here's a nice, clean way:

class Parser
{
public:
   typedef double matrix[4][4];

   // ...

   const matrix& getMatrix() const
   {
      return matrix_;
   }

   // ...

private:
  matrix matrix_;
};

现在你和一个描述性的类型名称,而不是一个数组的工作,但因为它是一个的typedef 编译器将仍然允许它传递给接受不可改变的API函数基本类型。

Now you're working with a descriptive type name rather than an array, but since it's a typedef the compiler will still allow passing it to the unchangeable API function that takes the base type.

这篇关于如何处理C ++中的数组(堆栈上声明)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆