C++ 重载运算符<对于结构:错误太多参数

编程入门 行业动态 更新时间:2024-10-23 12:28:11
本文介绍了C++ 重载运算符<对于结构:错误太多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于一项作业,学生必须制作一个 Card 结构来保存卡片的套装、等级和位图.这个结构需要一个重载的<"运算符比较lhs卡的Rank是否小于rhs卡并返回bool.到目前为止,这是我的 Card.h 文件:

For an assignment students have to make a Card struct that keeps the Suit, Rank and Bitmap of a Card. This struct needs an overloaded "<" operator to compare whether the lhs Card's Rank is smaller than the rhs Card and return the bool. So far this is my Card.h file:

#pragma once #include "GameEngine.h" struct Card { public: //Constructor and Destructor Card(); virtual ~Card(); //Methods bool operator< (const Card& lhs, const Card& rhs) { return (lhs.m_Rank < rhs.m_Rank); } //Enumerations enum class Suit { Diamonds, Clubs, Hearts, Spades, }; enum class Rank { RankAce, RankTwo, RankThree, RankFour, RankFive, RankSix, RankSeven, RankEight, RankNine, RankTen, RankJack, RankQueen, RankKing, }; private: //Datamembers Bitmap *m_BmpPtr; Rank m_Rank; Suit m_Suit; };

但是操作符<过载声称它有太多的参数.这不是确保可以在一次重载中比较 lhs 和 rhs 的正确方法吗?不是说我要分开吧?

However the operator< overload claims that it has too many parameters. Isn't this the right way to make sure both lhs and rhs can be compared in one overload? It's not like I have to split it up right?

非常感谢.

推荐答案

编译器认为这是一个成员函数,但成员函数operators不能有多个参数.第一个参数是隐式的 *this 而第二个是你提供的.

The compiler think this is a member function, but member function operators cannot have more than one argument. The first argument is implicitly *this while the second is the one you supply.

您可以通过剥离第一个参数并使用 *this 代替 lhs 来使其成为成员函数.否则,您可以使用惯用的解决方案并使其成为朋友:

You can make this a member function by stripping the first argument and using *this in place of lhs. Otherwise, you can use an idiomatic solution and make it a friend:

friend bool operator< (const Card& lhs, const Card& rhs) { return lhs.m_Rank < rhs.m_Rank; }

更多推荐

C++ 重载运算符<对于结构:错误太多参数

本文发布于:2023-06-03 12:17:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473757.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:太多   运算符   错误   参数   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!