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

查看:128
本文介绍了如何处理在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]);

我想出的唯一方法是调用者将数组结果传递给函数使成员公开:

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_);
}

这是唯一的办法吗?我惊讶于如此不灵活的多维数组声明像这样。我认为 matrix _ 本质上与一个 double ** 相同,我可以(安全地)两者之间。事实证明,我甚至不能找到一种不安全的方式在事情之间施展。说我在 Parser 类中添加一个访问器:

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_;
}



这将编译,但我不能使用它, t似乎是一种回到weirdo数组类型的方法:

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:'type cast':无法从'void *'转换为'const double [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.

可以肯定的是,在这一点上,这个问题纯粹是学术性的,因为 void

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_;
};

现在您正在使用描述性类型名称而不是数组, c $ c> 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天全站免登陆