[英]Defining two-argument operator overload for private struct
我试图重载运算符,以使私有结构的容器只能在该类中使用(将std::deque<T>
与std::vector<T>
与operator==()
)。
我习惯于声明操作符重载,如下所示。
正如我所期望的那样,此命令将打印“ 1”,但是该结构是公共的。
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
class Example1 {
public:
struct S1 {
bool flag;
unsigned value;
S1(const unsigned value) :
flag(false), value(value)
{
// Empty
}
bool operator==(const S1 &rhs) const {
return flag == rhs.flag && value == rhs.value;
}
};
static void test();
};
inline bool operator==(const std::deque<Example1::S1> &d, const std::vector<Example1::S1> &v) {
return d.size() == v.size() && std::equal(d.begin(), d.end(), v.begin());
}
inline bool operator==(const std::vector<Example1::S1> &v, const std::deque<Example1::S1> &d) {
return d == v;
}
void Example1::test() {
std::vector<S1> v1 { 1, 2, 3, 4 };
std::deque<S1> d1 { 1, 2, 3, 4 };
std::cout << (v1 == d1) << "\n";
}
int main() {
Example1::test();
}
当结构是私有的时,我应该如何定义这些运算符?
我尝试了以下方法。
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
class Example2 {
public:
static void test();
private:
struct S2 {
bool flag;
unsigned value;
S2(const unsigned value) :
flag(false), value(value)
{
// Empty
}
bool operator==(const S2 &rhs) const {
return flag == rhs.flag && value == rhs.value;
}
};
bool operator==(const std::deque<S2> &d, const std::vector<S2> &v) const {
return d.size() == v.size() && std::equal(d.begin(), d.end(), v.begin());
}
bool operator==(const std::vector<S2> &v, const std::deque<S2> &d) const {
return d == v;
}
};
void Example2::test() {
std::vector<S2> v1 { 1, 2, 3, 4 };
std::deque<S2> d1 { 1, 2, 3, 4 };
std::cout << (v1 == d1) << "\n";
}
int main() {
Example2::test();
}
但是重载只能有一个参数:
main.cpp:25:72: error: ‘bool Example2::operator==(const std::deque&, const std::vector&) const’ must take exactly one argument
bool operator==(const std::deque<S2> &d, const std::vector<S2> &v) const {
您当前的尝试尝试重载Example2::operator==
,这不能使用两个参数来完成。
一个简单的解决方案是将那些运算符定义为Example2
类的朋友 :
friend bool operator==(const std::deque<S2> &d, const std::vector<S2> &v) {
return d.size() == v.size() && std::equal(d.begin(), d.end(), v.begin());
}
friend bool operator==(const std::vector<S2> &v, const std::deque<S2> &d) {
return d == v;
}
这会将功能定义为非成员功能。
您可以使用友谊:
friend bool operator==(const std::deque<S2> &d, const std::vector<S2> &v) {
return d.size() == v.size() && std::equal(d.begin(), d.end(), v.begin());
}
friend bool operator==(const std::vector<S2> &v, const std::deque<S2> &d) {
return d == v;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.