[英]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.