【发布时间】:2020-07-19 08:45:01
【问题描述】:
尊敬的 StackOverflow 社区,
将类型 Couple 定义如下:
class Couple
{
public:
Couple(Thing* aa, Thing* bb) : a(aa), b(bb) {};
public:
bool operator == (const Couple& rhs) const { return this->a->unique_id == rhs.a->unique_id && this->b->unique_id == rhs.b->unique_id; }
bool operator != (const Couple& rhs) const { return this->a->unique_id != rhs.a->unique_id || this->b->unique_id != rhs.b->unique_id; }
bool operator <= (const Couple& rhs) const { return this->a->unique_id < rhs.a->unique_id || this->a->unique_id == rhs.a->unique_id && this->b->unique_id <= rhs.b->unique_id; }
bool operator >= (const Couple& rhs) const { return this->a->unique_id > rhs.a->unique_id || this->a->unique_id == rhs.a->unique_id && this->b->unique_id >= rhs.b->unique_id; }
bool operator < (const Couple& rhs) const { return this->a->unique_id < rhs.a->unique_id || this->a->unique_id == rhs.a->unique_id && this->b->unique_id < rhs.b->unique_id; }
bool operator > (const Couple& rhs) const { return this->a->unique_id > rhs.a->unique_id || this->a->unique_id == rhs.a->unique_id && this->b->unique_id > rhs.b->unique_id; }
operator Couple() const { return *this; }
public:
Thing* a;
Thing* b;
};
我正在尝试使用 c++ std::find 函数:
std::vector<Couple*> generate_couples(std::vector<Thing*> things)
{
std::vector<Couple*> couples;
for (unsigned int i = 0; i < things.size(); i++)
{
for (unsigned int j = 0; j < things.size(); j++)
{
if (things[i] != things[j] && match(things[i], things[j]))
{
Couple c = Couple(things[i], things[j]);
Couple rc = Couple(things[j], things[i]);
auto it_c = std::find(couples.begin(), couples.end(), c);
auto it_rc = std::find(couples.begin(), couples.end(), rc);
if (it_c == couples.end() && it_rc == couples.end())
couples.push_back(&c);
}
}
}
return couples;
}
Visual Studio Community 2017 报错:
错误 C2679 二进制“==”:未找到采用“const _Ty”类型右侧操作数的运算符(或没有可接受的转换)
源自文件的第 3520 行
c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xutility
我已经重载了所有比较运算符,包括“==”,我一直在尝试重载 conevrsion 运算符,因为它在错误的最后部分中有所说明。我还尝试在类外定义operator == 并将其声明为友元函数:
bool operator == (const Couple& lhs, const Couple& rhs)
{ return lhs.a->unique_id == rhs.a->unique_id && lhs.b->unique_id == rhs.b->unique_id; }
class Couple
{
// ...
friend bool operator == (const Couple& lhs, const Couple& rhs);
// ...
};
它会引发错误:
E0344 这个算子函数的参数太多
有几个相关的问题,最相似的一个是这个(How to use std::find/std::find_if with a vector of custom class objects?),但我在那里找不到我的问题的解决方案。
提前感谢任何 cmets 和答案!
【问题讨论】:
-
couples.push_back(&c);-- 像这样存储局部变量的地址是未定义的行为。在循环的下一次迭代中会发生什么,当c你的地址要么被回收,要么在一阵烟雾中消失并消失? -
无关:
operator Couple() const { return *this; }永远不会被使用,因此您可以将其删除。 -
同样,但不相关,当重载关系运算符时,您真正需要完全实现的只是运算符
<和==。所有其他的都可以用<和==来实现。这样做的原因是,如果<和==很复杂,那么您不会试图弄清楚如何将事情从里到外来实现!=、>=等。例如:@ 987654341@ 比试图以困难的方式反转==的错误要容易得多。 -
Here is an example of the relational operators。请注意所有其他运算符的简化,而不是试图找出逆运算。
-
哇,谢谢@PaulMcKenzie!这是有道理的:)
标签: c++ find operator-overloading