[英]Overloading operator not working in C++
為什么下面的代碼總是返回數組中的最后一個播放器?
運算符bool operator > (Player &P) { return Age > P.Age; }
bool operator > (Player &P) { return Age > P.Age; }
似乎無法正常工作。 我將其視為“將左側對象中元素的年齡與右側對象中元素的年齡進行比較”。 有什么建議么?
注意:我不打算使用std::vector
或std::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();
}
這是因為您在比較指針( Player*
)而不是Player
實例。 要獲得所需結果的最簡單解決方法是取消引用:
if (*Current > *Oldest) {
這將為Player
類調用operator>
實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.