重载'++'运算符C ++

问题描述 投票:0回答:2

我重载了'++'运算符,我在head和.cpp文件中定义了它。我在主文件中使用运算符。它说它没有定义,所以我很困惑为什么编译器看不到它。我确保包括一个复制构造函数,因为在先前的项目中遇到该错误。

player.h

#pragma once
class Player {
private:
int hitsGotten;
int winHits;
int score;

public:
//Constructor
Player(int hits);
Player();
Player(const Player& play);

int gethits() { return hitsGotten; };
int getWinHits() { return winHits; }
int getScore() { return score; };

void setScore(int num) { score = num; };

virtual void gothit() { hitsGotten++; };
virtual void WonGame() { score++; };

void operator++();
};

player.cpp

 #include "player.h"

 Player::Player(int hits) {
     winHits = hits;
     hitsGotten = 0;
     score = 0;
  }

  Player::Player(){
     winHits = 0;
     hitsGotten = 0;
     score = 0;
 }    

  Player::Player(const Player& play){
     hitsGotten = play.hitsGotten;
     winHits = play.winHits;
     score = play.score;

  }

  void Player::operator++(){
      this->score = this->score + 1;
  }    

主程序

 #include "board.h"
 #include "game.h"
 #include "player.h"
 #include "humanPlayer.h"
 #include <vector>
 #include <iostream>

 using namespace std;

 vector<Game> list;

 int main() {

int diff;
int BX = 0;
int BY = 0;
int totalHits = 0;

if (diff == 1) {
    cout << "You have selected Easy" << endl;
    BX = 5;
    BY = 5;
    totalHits = 8;
}
else if (diff == 2) {
    cout << "You have selected Standard" << endl;
    BX = 8;
    BY = 8;
    totalHits = 17;
}
else if (diff == 3) {
    cout << "You have selected Hard" << endl;
    BX = 10;
    BY = 10;
    totalHits = 21;
}
else {
    cout << "The difficulty was not selected correctly"
        << "Please take out the game and blow the dust off" << endl;
}

Game G(BX, BY);
Board B(BX, BY);
humanPlayer User(totalHits);
Player Computer(totalHits);


G.startGame();
//G.LossScreen();
//G.WinScreen();
//G.anotherGame();;

if (diff == 1) {
    G.gameSetUpE(B, User);
}
else if (diff == 2) {
    G.gameSetUpS(B, User);
}
else if (diff == 3) {
    G.gameSetUpH(B, User);
}
else {
    cout << "Something went wrong with the game set up"
        << "Please take out the game and blow the dust off" << endl;
}

cout << "Time to start the game" << endl;

int gameRes = G.playGame(B, User, Computer);

G.setWinner(gameRes);

list.push_back(G);

if (gameRes == 1) {
    G.WinScreen();
    User++;
    if (G.anotherGame() == 'Y') {
        main();
    }
    else {
        G.endGame(list);
        G.ByeScreen();
    }
}
if (gameRes == 2) {
    G.LossScreen();
    Computer++;
    if (G.anotherGame() == 'Y') {
        main();
    }
    else {
        G.endGame(list);
        G.ByeScreen();
    }
}

return 0;

}

“错误报告”

c++ operator-overloading
2个回答
0
投票

operator++()声明前缀增量运算符。允许像++x一样使用。 x++是另一种函数,您尚未在类中声明/定义过。要定义后缀增量运算符,请使用参数int声明一个新函数:

void operator++(int);

int添加到您的声明和定义中,并且您的代码应进行编译(如果这是唯一的问题,那就是。)>


0
投票

您已定义了前递增++运算符(例如++ i)而不是后递增(例如i ++)。因此,您可能

© www.soinside.com 2019 - 2024. All rights reserved.