pair 的 first 和 second 真的很丑,那么能不能对其进行重命名呢?
答案是没问题,我们通过引用实现之。
pair 的头文件
最省略写法:
#include
#include
using namespace std;
struct Node : public std::pair<int, int> {
int &x = first;
int &y = second;
// explicit Node() = default;
// virtual ~Node() = default;
// Node(const Node &) = default;
// Node &operator=(const Node &) = delete;
};
int main() {
Node tmp;
cout << tmp.x << endl
<< tmp.y;
}
注释掉的部分便是 c++11 对其的处理方式,你不用写出来。
优点:写的内容很少
缺点:只能默认构造,之后再赋值
多写一点:
#include
#include
using namespace std;
struct Node : public std::pair<int, int> {
int &x = first;
int &y = second;
explicit Node() = default;
virtual ~Node() = default;
Node(const Node &) = default;
Node &operator=(const Node &) = delete;
Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
};
int main() {
Node tmp(make_pair(1, 2));
cout << tmp.x << endl
<< tmp.y;
}
我们加入传入父类的构造函数,使其可以通过 pair 的构造函数而进行初始化
优点:能进行初始化
缺点:有构造临时 pair 的时间开销,不能拷贝赋值
再多写一些:
#include
#include
using namespace std;
struct Node : public std::pair<int, int> {
int &x = first;
int &y = second;
explicit Node() = default;
virtual ~Node() = default;
Node(const Node &) = default;
Node &operator=(const Node &) = delete;
Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
Node(int argx, int argy) : x(first), y(second), pair(argx, argy) {}
};
int main() {
Node tmp(1, 2);
cout << tmp.x << endl
<< tmp.y;
}
我们只传入数值,并使用 pair 的构造函数
优点:同版本2
缺点:不能拷贝赋值
#include
#include
using namespace std;
struct Node : public std::pair<int, int> {
int &x = first;
int &y = second;
explicit Node() = default;
virtual ~Node() = default;
Node(const Node &) = default;
Node &operator=(const Node &arg) { return x = arg.x, y = arg.y, *this; }
Node(const pair<int, int> &arg) : x(first), y(second), pair(arg) {}
Node(int argx, int argy) : x(first), y(second), pair(argx, argy) {}
};
int main() {
Node tmp(1, 2);
Node tmp2 = tmp;
cout << tmp2.x << endl
<< tmp2.y;
}
缺点:无