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;
}
相关文章