【问题标题】:How to return const Float** from a C++ function如何从 C++ 函数返回 const Float**
【发布时间】:2010-11-11 15:33:02
【问题描述】:

我有一个包含数组“float ** table”的类。现在我想让成员函数返回它,但不希望它在类之外被修改。所以我这样做了:

class sometable 
{
  public:
   ...
   void updateTable(......);
   float **getTable() const {return table;}
  private:
    ...
    float **table;
}

当我使用常量对象调用 getTable 时,这编译正常。现在我试着 通过将 getTable 声明为“const float **getTable()”来使其更安全。我有 以下编译错误:

Error:
  Cannot return float**const from a function that should return const float**.

为什么?如何避免在课堂外修改表格?

【问题讨论】:

  • Pointer to pointer to 指向.....看起来是个糟糕的设计。这是 C++ - 使用 std::vector 并返回引用。

标签: c++ constants


【解决方案1】:

像这样声明你的方法:

float const* const* getTable() const {return table;}

const float* const* getTable() const {return table;}

如果你愿意的话。

【讨论】:

    【解决方案2】:

    您不能将 float** 分配给 float const**,因为它允许修改 const 对象:

    float const pi = 3.141592693;
    float* ptr;
    float const** p = &ptr; // example of assigning a float** to a float const**, you can't do that
    *p = π  // in fact assigning &pi to ptr
    *ptr = 3;  // PI Indiana Bill?
    

    C 和 C++ 规则对允许的内容有所不同。

    • C++ 规则是,当您在星号之前添加一个 const 时,您必须在后面的每个之前添加一个 const。

    • C 规则是你只能在最后一个星之前添加一个 const。

    在这两种语言中,您只能在最后一个星号之前删除 const。

    【讨论】:

    • 好吧,我的规则只适用于添加,而不是删除。在 C++ 和 C 中,您只能在最后一个星号之前删除 const(我也已将此添加到上面的规则中)。见 4.4/4(我的例子实际上是标准的例子)
    • 我已经删除了我之前的评论,因为它是基于对您的回答的误解。
    【解决方案3】:

    你可以将你的方法声明为

    const float * const * const getTable() const {return table;}
    

    但即使这样(最外面的 const - 函数名旁边)也不会阻止客户端尝试删除它。 您可以改为返回引用,但最好是对表使用 std::vector 并将 const ref 返回给它 - 除非必须使用 C 样式数组

    【讨论】:

    • “开发人员有更好的事情要做,而不是故意破坏他们的 API。” :)
    • 虽然您返回对std::vector的引用是正确的
    • 最后一个 const 不是必需的,它确实改变了可以用返回值做什么。
    • 当然 - 最后一个 const 只是语法糖,它将是一个右值。尽管付出了所有努力,客户仍然可以打破它,因为在 C++ 中你拥有“完全”控制权
    【解决方案4】:

    虽然您可以像这样清楚地键入语法,但我发现为多维数组定义一些 typedef 更具可读性。

    struct M {
        typedef double* t_array;
        typedef const double t_carray;
        typedef t_array* t_matrix;
        typedef const t_carray* t_cmatrix;
    
        t_matrix values_;
    
        t_cmatrix values() const { return values_; }
        t_matrix  values()       { return values_; }
    };
    

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 2022-01-14
      • 2016-06-10
      • 1970-01-01
      相关资源
      最近更新 更多