【问题标题】:Pass array to object method将数组传递给对象方法
【发布时间】:2012-01-20 12:02:36
【问题描述】:

我遇到了一个我似乎无法理解的基本数组问题。

我有一个类“StaticDisplayLayer”,构造函数有 2 个参数 - 一个 int 和一个指向 3 个无符号短整数数组的指针:

//constructor definition:
StaticDisplayLayer(int type, unsigned short *displayColor[3]);

//constructor code:
StaticDisplayLayer::StaticDisplayLayer(int type, unsigned short *dColor[3]) : DisplayLayer(type)
{
    displayColor = dColor;
}

我正在尝试使用以下内容创建该类的实例:

unsigned short layerColor[3] = {(unsigned short)255,(unsigned short)255,(unsigned short)255};
StaticDisplayLayer myLayer(1, &layerColor);

我的理解是 &layerColor 是指向 layerColor 数组的指针,但是编译器给了我以下错误:

no matching function for call to `StaticDisplayLayer::StaticDisplayLayer(int, short unsigned int (*)[3])'
Candidates are:
   StaticDisplayLayer::StaticDisplayLayer(const StaticDisplayLayer&)
   StaticDisplayLayer::StaticDisplayLayer(GLenum, short unsigned int**)

我知道第二个候选者是我正在尝试使用的候选者,但显然我不理解指向数组的指针的概念。如果有人可以阐明如何调用该构造函数和/或任何解释这一点的资源,我将不胜感激 - 到目前为止,我的在线搜索并没有真正出现。

【问题讨论】:

  • 您是否考虑过为此使用std::vector?你可以用它绕过所有那些复杂的语法。
  • 是的,我正要使用矢量重写它,但不想在不了解我做错了什么的情况下就放手。

标签: c++ arrays parameter-passing


【解决方案1】:

unsigned short *dColor[3] 不是指向数组的指针,而是指向指针数组的指针。 [3] 被忽略并替换为另一个指针,因为它是一个函数参数。换句话说,它衰减。要创建指向数组的指针,请使用unsigned short (*dColor)[3],它是指向unsigned short 的大小为3 的数组的指针。

在 C++ 中一个更好的想法是使用对数组的引用:

unsigned short (&dColor)[3]

只需传递layerColor

【讨论】:

    【解决方案2】:

    &layerColor 的类型为 pointer to array of 3 unsigned shorts。另一方面,您的构造函数需要unsigned short *[3],即array of three pointers to unsigned short。事实上,作为函数参数类型,它是一个pointer to pointer to unsigned short - 维度被完全忽略。我认为您的意思是让您的构造函数只获取指向 unsigned short 的指针并传递 layerColor

    StaticDisplayLayer(int type, unsigned short *displayColor);
    
    unsigned short layerColor[3] = {255,255,255};
    StaticDisplayLayer myLayer(1, layerColor);
    

    请注意,在这种情况下,调用者有责任传递一个至少包含 3 个元素的数组。或者,您可以通过

    使函数采用正好 3 个 ushorts 的数组
     StaticDisplayLayer(int type, unsigned short (&displayColor)[3]);
    

    但在这种情况下,您将无法传递动态分配的数组。

    我不得不注意到你缺乏一定的C++基础知识,所以我建议你阅读good C++ book

    【讨论】:

    • 我订购了 Stroustrup 的书 :)
    • @TheOx:Lippman 的 C++ Primer 更好。 Stroustup 的不是教科书,而是参考
    【解决方案3】:

    unsigned short displayColor[3] 本质上是一组 unsigned short 指针或 unsigned short *

    unsigned short layerColor[3] 是一个 unsigned short 数组,而不是一个 unsigned short 指针数组。

    我会改为为颜色创建一个结构或类,然后传递一个指针或引用。

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 2016-01-14
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多