无法访问类之间的数据成员

时间:2015-08-08 15:05:05

标签: c++ class organization

我有两节课;球员类和比赛类。我希望玩家能够使用其所有成员函数;携带,捕获等,但其成员函数需要知道匹配类数据成员;董事会,对手,挑战者没有公开这些数据成员。

如果你找不到一个好的解决方案或者对我的要求感到困惑,我仍然会对课堂组织方面的建议感兴趣。

mancala.h

#ifndef MANCALA_H
#define MANCALA_H

#include <string>
#include <random>

namespace mancala{  

    class player{
        public:
            void carry(int pit);
            void capture(const int& pit);
            bool madeStore(const int& pit)const;
            bool madeCapture(const int& pit)const; 
            bool madeValidMove(const int& pit)const;
            bool madeSideClear()const;
            bool operator==(const player& p)const;
        private:
            std::string tag;
    };

    class match{
        public:
            match(const int& match_ID = 0) : board{4,4,4,4,4,4,0,4,4,4,4,4,4,0}{
                if(match_ID){
                    ;
                }
                else{
                    this->turn = randPlayer();
                    this->status = "make move";
                }
            };
            void begin();
            void end();
            void save();
            bool update();
        private:
            player challenger, opponent, turn;
            static const int seeds = 48;
            static const int pits  = 14;
            std::string status;
            int board[pits];
            void nextTurn();
            player randPlayer();
    };
}

#endif//MANCALA_H

示例来自:mancala.cpp

void player::carry(int pit)
{
    if(this->madeValidMove(pit) == false){
        status = "invalid move";
    }
    else{

        int hand = board[pit];

        board[pit] = 0;

        for(hand; hand != 0; hand--){  

            if(pit == 13){
                pit = 0;
            }
            else{
                pit++;  
            }
             //Skips opponent store
            if(pit == 13 && turn == challenger){
                pit = 0;
            }//Skips challenger store
            else if(pit == 6 && turn == opponent){
                pit++;
            }
             //If placing last seed check where it is being placed
            if(hand == 1){
                 //Store
                if(this->madeStore(pit)){
                    board[pit]++;
                    status = "free move";
                }//Capture
                else if(this->madeCapture(pit)){
                    this->capture(pit);
                  nextTurn();
                }//Normal
                else{
                    board[pit]++;
                    nextTurn();
                }
            }//Placing seed
            else{
                board[pit]++;
            }
        }

        if(this->madeSideClear()){
            end();
        }
    }   

    save();
}

1 个答案:

答案 0 :(得分:0)

让匹配类成为玩家类的朋友。

https://en.wikipedia.org/wiki/Friend_class

  

C ++中的友好类可以访问声明为朋友的类的“私有”和“受保护”成员。