比较/复制 COORD 结构;超载

发布于 2024-10-19 17:45:02 字数 175 浏览 0 评论 0原文

这看起来微不足道,但无休止的搜索并没有给出答案。

我需要比较和分配。

如果无法添加成员函数或友元函数,如何重载 COORD?

使用这种基于 Windows 的结构只是不好的风格吗?

另外,我知道我可以编写自己的类(或者只为每个成员执行一次操作),但这个问题确实让我想知道。

This seems trivial yet endless searching doesn't yield an answer.

I need to compare and assign.

How can I overload the COORD if I can't add a member function or friend a function?

is it just bad style to use this windows based structure?

Also, I know I can write my own class(or just do the operation once for each member), but this problem just really has me wondering.

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

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

发布评论

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

评论(2

兰花执着 2024-10-26 17:45:02

COORD 仅具有公共成员,因此不需要友元函数 - 自由运算符就足够了:

bool operator <(COORD const& lhs, COORD const& rhs)
{
    return lhs.Y < rhs.Y || lhs.Y == rhs.Y && lhs.X < rhs.X;
}

bool operator ==(COORD const& lhs, COORD const& rhs)
{
    return lhs.X == rhs.X && lhs.Y == rhs.Y;
}

COORD 有隐式复制 c'tor 和 operator= 已经,不需要定义那些。

COORD only has public members, so there's no need for friend functions -- free operators should suffice:

bool operator <(COORD const& lhs, COORD const& rhs)
{
    return lhs.Y < rhs.Y || lhs.Y == rhs.Y && lhs.X < rhs.X;
}

bool operator ==(COORD const& lhs, COORD const& rhs)
{
    return lhs.X == rhs.X && lhs.Y == rhs.Y;
}

COORD has an implicit copy c'tor and operator= already, no need to define those.

三五鸿雁 2024-10-26 17:45:02

为什么不从 public COORD 派生您的 on 类并添加所需的语句? C++ 中的structclass 相同,只是默认情况下所有成员都是public

struct MyCoord : public COORD
{
  // I like to have a typedef at the beginning like this
  typedef COORD Inherited;
  // add ctor, if you like ...
  MyCoord(SHORT x, SHORT y)
    : Inherited::X(x)
    , Inherited::Y(y)
  { }
  // no need for copy ctor because it's actually POD (plain old data)

  // Compatibility ... ;)
  operator COORD&()
  {
      return *this; // may need cast
  }

  COORD* operator&()
  {
     return this; // may need cast
  }
  // declare friends ...
}

Why not derive your on class from public COORD and add the required statements? struct in C++ is just the same as class, except that by default all members are public.

struct MyCoord : public COORD
{
  // I like to have a typedef at the beginning like this
  typedef COORD Inherited;
  // add ctor, if you like ...
  MyCoord(SHORT x, SHORT y)
    : Inherited::X(x)
    , Inherited::Y(y)
  { }
  // no need for copy ctor because it's actually POD (plain old data)

  // Compatibility ... ;)
  operator COORD&()
  {
      return *this; // may need cast
  }

  COORD* operator&()
  {
     return this; // may need cast
  }
  // declare friends ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文