类之间的比较

Comparing between classes

本文关键字:比较 之间      更新时间:2023-10-16

我得到了一个创建1-6之间数字的类和另一个将数字放入数组的类。如果两个数组相同,我如何比较它们?(这样评论行就行了)

#include <iostream>
#include <ctime>
#include <cstdlib>
class dice {
private:
    unsigned int number;
public:
    dice() {
        (*this).number = (rand() % 6) + 1;
        return;
    }
};
class dicemng {
private:
    unsigned int dice_count;
    dice* arr_dice;
public:
    dicemng(unsigned int k = 0) : dice_count(k) {
        arr_dice = new dice[dice_count];
        return;
    }
};
int main() {
    srand(time(nullptr));
    dicemng w1(5), w2(5);
    //std::cout << (w1 == w2) << std::endl;
    return 0;
}

谢谢你的帮助!

类中需要一个operator ==,如下所示:

class dicemng {
    // ...
public:
    bool operator ==(const dicemng &other) const {
        if (dice_count != other.dice_count) return false;
        for (unsigned i = 0; i < dice_count; ++i)
            if (!(arr_dice[i] == other.arr_dice[i])) return false;
        return true;
    }
};

当然,也为类骰子提供operator ==

class dice {
    // ...
public:
    bool operator ==(const dice &other) const {
        return number == other.number;
    }
};

建议还为两个类提供operator !=,这样您也可以比较不相等性:

class dice {
    // ...
public:
    bool operator !=(const dice &other) const {
        return !(*this == other);
    }
};
class dicemng {
    // ...
public:
    bool operator !=(const dicemng &other) const {
        return !(*this == other);
    }
};

Btw。dicemng类存在内存泄漏(它不会释放内存),因此您还应该提供一个析构函数,并删除构造函数中分配的数组。为了完全正确,您需要提供或禁用复制构造函数和赋值运算符。这就是为什么使用std::vector会更好,你会省去一些头痛;)

通过使用std::vector并定义dicemng::operator==来使用std::vector::operator==:

#include <vector>
class dicemng {
private:
    // `dice_count` becomes redundant since you can get it with `arr_dice.size()`
    std::vector<dice> arr_dice;
public:
    dicemng(unsigned int k = 0) : arr_dice(k) { }
    bool operator==(dicemng const& rhs) const { // `rhs` == "right hand side"
        return arr_dice == rhs.arr_dice; // Compares the contents of the vectors
    }
    // Common sense says if we define `operator==` we should also define `operator!=`:
    bool operator!=(dicemng const& rhs) const {
        return !(*this == rhs); // Implemented in terms of `operator==`
    }
};
int main() {
    srand(time(nullptr));
    dicemng w1(5), w2(5);
    std::cout << (w1 == w2) << std::endl;
    return 0;
}