我有一个类,它创建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;
}
感谢您的帮助!
答案 0 :(得分:3)
课程中你需要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);
}
};
顺便说一下。类dicemng有一个内存泄漏(它不释放内存),所以你应该提供一个析构函数并删除在构造函数中分配的数组。要完全正确,您需要提供或禁用复制构造函数和赋值运算符。这就是为什么std::vector
的使用会更好,你会省去一些头疼的事情;)
答案 1 :(得分:1)
使用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;
}