C ++重载操作符< for struct:错误太多参数 [英] C++ Overloading operator< for struct: Error too many parameters

查看:145
本文介绍了C ++重载操作符< for struct:错误太多参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于作业,学生必须制作一个Card结构,保持卡片的西装,排名和位图。此结构需要重载的<运算符比较lhs卡的等级是否小于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 ++重载操作符&lt; for struct:错误太多参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆