从另一个类访问变量/函数

Accessing variables/functions from another class

本文关键字:函数 变量 访问 另一个      更新时间:2023-10-16

我正在制作一个纸牌游戏,我有几个类。我有一个手牌类,一个玩家类,一个"列"类(纸牌在手牌之后被放置在屏幕上),我需要每个类都能访问其他类的变量。

class Hand
{
private:
    int **Hx,Hy;** //Hand X, Hand Y
    int HAmount;//Amount of cards in Hand
    int HOwner; //Player 1/2
    int Limit; //Limit of cards in Hand
    int HContents[8]; //Card Position in 54 card deck NOT card value.
    bool Removed;
public:
    Hand();
    void Lim();
    void Get_Card();
    void Show();
    void Set_Values(int y, int Own);
};

然后在另一个类中,我需要访问上面的一些变量。

void Card::show()
{
    if((apply == true)
    {
        if((Track == true)&&(SelNum == TNum)&&(TOwner == COwner))
        {
            ScnPos = TAmount;
            x = Tx;
            y = Ty + ScnPos*10;
        }
        if((Hand == true)&&(**HOwner** == COwner))
        {
            x = **Hx** + ScnPos*45;
            y = **Hy;**
        }
        apply_surface(x,y,Cards,Screen,&Clip[Pos]);
    }
}

我试过用班级友谊和其他方法,但我不能使它工作。(显然我有更多的变量需要同样的处理)(忽略代码中的任何错误)

代码中的错误才是真正的问题。Card没有理由访问Hand的私有成员。这是设计错误,你的其他问题只是想告诉你。

那么,您应该将getterssetters作为变量。例如:

class Test {
    private: int a;
    public: int GetA() {
       return this->a;
    }
    void SetA(int a) {
       this->a = a;
    }
}