类之间的比较
Comparing between classes
我得到了一个创建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;
}
相关文章:
- 禁止指针和整数之间的比较C++
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 比较它们之间的元素并获取公共值的键
- 零点和布尔值之间的比较
- 我的 c++ 程序似乎没有发现字符串和我拥有但输入使用 getline 的变量之间的比较
- C++ - 负数和正数之间的比较返回 false
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- C++模板参数之间的比较似乎被忽略了
- 为什么C++容器之间存在比较运算符
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较
- 数字之间的比较
- C++ - 比较模板和类之间的数据类型
- 获取字符串大小的各种方法之间的比较
- 比较器的两个实现之间的差异
- 如何修复C++中的"指针和整数之间的比较"错误?
- 不同指针类型之间的无效比较:'type*' 和 'type&(*)()'
- 符号和未签名整数表达式之间的比较,以进行循环误差
- 比较C 中移动和智能指针之间的习惯
- Python,C ,C#和Java中的字符串比较之间的差异
- 与表达式或变量进行比较之间的性能差异