简体   繁体   English

重载运算符在C ++中不起作用

[英]Overloading operator not working in C++

Why is it that below code is always returning the last player in the array? 为什么下面的代码总是返回数组中的最后一个播放器?

The operator bool operator > (Player &P) { return Age > P.Age; } 运算符bool operator > (Player &P) { return Age > P.Age; } bool operator > (Player &P) { return Age > P.Age; } seems not to be working properly. bool operator > (Player &P) { return Age > P.Age; }似乎无法正常工作。 I see it as "compare the age of the element in the left object to the age of the element in the right object". 我将其视为“将左侧对象中元素的年龄与右侧对象中元素的年龄进行比较”。 Any suggestions? 有什么建议么?

Note: I don't intend to use std::vector or std::string . 注意:我不打算使用std::vectorstd::string

#include <iostream>
using namespace std;

class Player {
    int Age;
    char *Name;
public:
    Player() {}
    void setName(char *n) { Name = n; }
    void setAge(int a) { Age = a; }
    bool operator > (Player &P) { return Age > P.Age; }
    void showName(){ cout << Name; }
};

int main()
{
    Player *ArrayPlayers = new Player[2];
    ArrayPlayers[0].setName("Player1");
    ArrayPlayers[0].setAge(27);
    ArrayPlayers[1].setName("Player2");
    ArrayPlayers[1].setAge(29);
    ArrayPlayers[2].setName("Player3");
    ArrayPlayers[2].setAge(24);

    Player *Oldest = &ArrayPlayers[0];
    for (int i = 0; i < 3; i++) {
        Player *Current = &ArrayPlayers[i];
        if (Current > Oldest) {
            Oldest = Current;
        }
    }

    cout << "Oldest player is: ";
    Oldest->showName();
    getchar();
}

It's because you are comparing pointers ( Player* ) not Player instances. 这是因为您在比较指针( Player* )而不是Player实例。 The simplest fix to achieve the desired result is to dereference: 要获得所需结果的最简单解决方法是取消引用:

if (*Current > *Oldest) {

This will invoke your operator> implementation for the Player class. 这将为Player类调用operator>实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM