c++ - 另一个类的友元类函数?

标签 c++

我正在尝试用 C++ 编写德州扑克游戏作为练习。我刚刚开始阅读有关好友功能的内容,并考虑使用它们来允许玩家从牌组中抽牌。

我目前定义了两个类,如下:

#include <string>
#include <vector>
#include <stdio.h>
typedef unsigned int uint;    

class deck

{
private:
    std::vector<card> cards;
public:
    void initialize(void)
    {
        char suits[] = { 'H', 'C', 'D', 'S' };
        uint values[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
        for (uint i = 0; i != 4; i++)
        {
            for (uint j = 0; j != 13; j++)
            {
                cards.push_back(card(suits[i], values[j]));
            }
        }
    }
    void shuffle(void)
    {
        uint i = cards.size(), random_index;
        card shuffled_card;
        while (i > 0)
        {
            random_index = rand() % (i + 1);
            shuffled_card = cards[random_index];
            cards[random_index] = cards[i];
            cards[i] = shuffled_card;
            i--;
        }
    }
};

class player
{
private:
    std::string name;
    uint chips;
    std::vector<card> hand;
public:
    player(std::string set_name, uint set_chips) { name = set_name; chips = set_chips; }
    void draw(deck& target_deck, uint number)
    {
        // Draw cards from the top of the 
        // target deck.
    }
};

我想要draw() player的方法类来引用 deck 的成员类,并且能够删除 number来自 cards 的卡片的deck 。自 cardsdeck 的私有(private)元素,我无法在 draw() 中引用它如target_deck.cards 。我尝试将好友功能添加到deck中类:

friend void player::draw(deck&target_deck, uint number);

但这并不能解决问题。代码是否有问题,或者是唯一的解决方案(a)在 player 之外定义友元函数或 (b) 制作整个 player类(class)好友 deck

提前感谢您的指点!

最佳答案

我将通过提供一个公共(public)函数deck::draw()来解决这个问题,该函数返回牌组中最上面的一张牌(并将其从牌组中删除)。然后,您可以根据需要多次调用 deck::draw() 来实现 player::draw()

如果您实现了 deck::draw(),那么您可能需要 deck::initialize() 在将 52 张新牌插入牌组之前清空牌组.

作为一个次要的风格注释,C++ 支持将 void 放入不带参数的函数的参数列表中的表示法,以向后兼容 C,但在新的 C++ 中并不常用代码。 C 支持它的原因是因为函数声明(原型(prototype))foo() 没有说明函数所采用的参数,而 foo(void) 表示该函数不采用任何参数。论据。 C++ 始终将 foo() 视为不带参数。

关于c++ - 另一个类的友元类函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23667542/

相关文章:

c++ - 使用 typeid 警告未使用的变量

带有可选参数的 C++ 构造函数

c++ - 没有函数模板的实例与参数列表匹配(试图打印数组)

c++基于键盘输入的退出循环

c++ - 使用条件变量超时的读写器锁

c++ - OpenGL 无法使用 VAO 过程更新顶点缓冲区

c++ - 单元测试资源管理类中的私有(private)方法 (C++)

c++ - 为什么qt不读取文件

c++ - 在 cygwin 中使用 make : "cannot execute binary file" 编译的 C 程序

c++ - 如何编写一个接受不同大小的特征矩阵的 std::vector 的函数?