C++封装数组

发布于 2024-10-30 23:26:47 字数 444 浏览 3 评论 0原文

抱歉,如果之前有人问过这个问题,但我找不到足够明确的答案。

在 C++ 中提供对数组成员的公共只读访问的正确方法是什么?

如果我有一个如下所示的类:

   
class Particle
{
    double _position[10];

public:
    double* get_position()
    {
       return _position;
    }
};
   

我想返回指向数组的指针真的很糟糕,因为这意味着它可以在 在类之外的任何时间,返回 const 指针就足够了吗?

我已经看到了有关在 C++ 中使用数组的其他问题,以及如何更好地选择使用向量,但我对这个问题真的很好奇。

正如你所看到的,我只是一个 C++ 菜鸟,如果这是一个愚蠢的问题,我很抱歉。

PD 抱歉我的英语不好。

Sorry if this has been asked before, but I can't find a clear enough answer.

What is the correct way to provide public read-only access to an array member in C++?

if i have a class like the following:

   
class Particle
{
    double _position[10];

public:
    double* get_position()
    {
       return _position;
    }
};
   

I guess is really bad to return a pointer to the array, since that means it can be changed at
any time outside of the class, is it enough to return a const pointer instead?

I have seen other questions about the use of arrays in C++, and how is a better option to use vectors, nevertheless I'm really curious about this issue.

As you can see I'm only a C++ noob, sorry if this is a stupid question.

P.D. Sorry for my bad English.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

电影里的梦 2024-11-06 23:26:48

您可以返回一个 const 指针:

class Particle
{
    double _position[10];

public:
    const double* get_position() const
    {
       return _position;
    }
};

请注意,我还将成员函数设置为 const(第二个 const),以告诉编译器可以在 const< 上调用此成员函数/code> Particle 实例。

注意:正如您已经提到的,更好的解决方案是使用 STL 向量等...

You can return a const pointer:

class Particle
{
    double _position[10];

public:
    const double* get_position() const
    {
       return _position;
    }
};

Note that I've also made the member-function const (the second const), to tell the compiler that this member-function may be called on const Particle instances.

Note: as you've already mentioned, a better solution is to use STL vectors and so on...

海拔太高太耀眼 2024-11-06 23:26:48

不要使用原始数组;总是更喜欢 std::array<> (或 boost::array 如果您的编译器不够新,无法附带 std::std::tr1 :: 实现):

class Particle
{
public:
    typedef std::array<double, 10> positions_t;

    Particle() : positions_() { }

    positions_t& get_positions() { return positions_; }
    positions_t const& get_positions() const { return positions_; }

private:
    positions_t positions_;
};

Don't use a raw array; always prefer std::array<> (or boost::array<> if your compiler is not recent enough to ship with a std:: or std::tr1:: implementation):

class Particle
{
public:
    typedef std::array<double, 10> positions_t;

    Particle() : positions_() { }

    positions_t& get_positions() { return positions_; }
    positions_t const& get_positions() const { return positions_; }

private:
    positions_t positions_;
};
少女七分熟 2024-11-06 23:26:48

与您想要提供访问权限的任何其他成员一样,您可以返回对其的 const 引用:

const double ( &get_position() const )[10] { return position; }

当然,您可能希望使用 typedef 使其更易于阅读。

或者,由于它是一个数组,您可以实现 operator[]

const double& operator[](std::size_t n) const { return position[n]; }

Like any other member that you want to provide access to, you can return a const reference to it:

const double ( &get_position() const )[10] { return position; }

Granted, you might want to use typedef to make that easier to read.

Or, since it is an array, you could implement operator[]:

const double& operator[](std::size_t n) const { return position[n]; }
假装不在乎 2024-11-06 23:26:48

是的,返回一个指向数组(或数组元素)的常量指针。

const double* get_position() const
{
    return _position;
} 

FWIW,我曾经使用 const 引用在类中实现了只读状态代码:(

class Foo
{
public:
    const int &     err = &errcode;

private:
    int             errcode;
    ...
}

如果语法不太正确,请道歉。)
这允许 Foo 的客户端读取但不能修改 Foo::err,它是对实际私有错误代码 Foo::errcode 的 const 引用,可由类的成员函数修改。

Yes, return a const pointer to the array (or array element).

const double* get_position() const
{
    return _position;
} 

FWIW, I once implemented a read-only status code within a class using a const reference:

class Foo
{
public:
    const int &     err = &errcode;

private:
    int             errcode;
    ...
}

(Apologies if the syntax is not quite correct.)
This allows the client of Foo to read, but not modify, Foo::err, which is a const reference to the actual private error code Foo::errcode, which is modifiable by the member functions of the class.

谁的年少不轻狂 2024-11-06 23:26:48

至少有三个问题/评论:

  • 返回数组
  • 返回元素
  • 返回 std::vector

返回数组

您始终可以返回指向数组的指针,但是在传递数组时,容量应该始终被指定。不幸的是,函数只能返回一个值,因此您必须从函数返回“out”参数:

double * get_position(unsigned int& capacity);
// Or
void  get_position(double *& array_pointer, unsigned int& capacity);

返回一个元素

您可以通过提供一个返回单个元素的函数来隐藏内部 {array} 表示。这提供了边界检查的优点。

  double get_one_position(unsigned int index)
  {
    double result = 0.0;
    if (index >= MAX_CAPACITY)
    {
       // Errror handling
    }
    else
    {
      result = _position[index];
    }
    return result;
  }

返回 std::vector

在 C++ 中,更喜欢 std::vector 而不是数组。您的问题是切换的原因之一。 std::vector 可以传递给方法并从方法返回。此外,std::vector 维护自己的容量变量,因此不需要将容量与数组指针一起传递。

  std::vector<double> _position(10);
  std::vector<double> get_positions(void)
  {
     return _position;
  }

总结

我建议您首先尝试对客户端或用户隐藏数组实现。如果无法做到这一点,最好使用 std::vector 而不是数组。最后使用数组。

返回数组时,始终附带一个容量变量。

There are at least three issues / comments:

  • Returning an array
  • Returning an element
  • Returning a std::vector

Returning an array

You can always return a pointer to the array, but when passing arrays, the capacity should always be specified. Unfortunately, functions can only return one value, so you will have to return "out" parameters from the function:

double * get_position(unsigned int& capacity);
// Or
void  get_position(double *& array_pointer, unsigned int& capacity);

Returning an element

You can hide the internal {array} representation by providing a function to return a single element. This gives an advantage of bounds checking.

  double get_one_position(unsigned int index)
  {
    double result = 0.0;
    if (index >= MAX_CAPACITY)
    {
       // Errror handling
    }
    else
    {
      result = _position[index];
    }
    return result;
  }

Returning a std::vector

In C++ prefer std::vector to an array. Your issue is one reason to switch. The std::vector can be passed to and returned from a method. Also, the std::vector maintains its own capacity variables, so there is no need to pass a capacity along with an array pointer.

  std::vector<double> _position(10);
  std::vector<double> get_positions(void)
  {
     return _position;
  }

Summary

I suggest you first try to hide the array implementation from the clients or users. If that cannot be done, prefer using std::vector to an array. Lastly use an array.

When returning an array, always accompany it with a capacity variable.

兮子 2024-11-06 23:26:47

返回 const* 也好不了多少,因为调用者可以直接放弃 constness。

考虑提供一个 const Iterator 而不是返回指针。这使您的班级的用户可以访问职位,而无需公开实现细节。如果您稍后想要从固定长度数组切换到 STL 容器,则可以这样做,而不会影响该类的用户。

Returning a const* isn't much better, as the caller can just cast the constness away.

Consider providing a const Iterator instead of returning a pointer. This gives users of your class access to positions without exposing the implementation details. If you later want to switch from a fixed-length array to a STL container, you can do so with no impact on users of the class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文