C++ STL--映射--添加字符串作为键,添加类对象作为值
代码解释了如何插入pair to map,其中键类型是string,值是对类对象的引用。但是,有3个重载函数,例如重载=运算符、重载<运算符和重载==运算符。。谁能解释一下为什么这里超载C++ STL--映射--添加字符串作为键,添加类对象作为值,c++,templates,dictionary,stl,C++,Templates,Dictionary,Stl,代码解释了如何插入pair to map,其中键类型是string,值是对类对象的引用。但是,有3个重载函数,例如重载=运算符、重载
#include <iostream>
#include <map>
using namespace std;
class AAA
{
friend ostream &operator<<(ostream &, const AAA &);
public:
int x;
int y;
float z;
AAA();
AAA(const AAA &);
~AAA(){};
AAA &operator=(const AAA &rhs);
int operator==(const AAA &rhs) const;
int operator<(const AAA &rhs) const;
};
AAA::AAA() // Constructor
{
x = 0;
y = 0;
z = 0;
}
AAA::AAA(const AAA ©in) // Copy constructor to handle pass by value.
{
x = copyin.x;
y = copyin.y;
z = copyin.z;
}
ostream &operator<<(ostream &output, const AAA &aaa)
{
output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl;
return output;
}
AAA& AAA::operator=(const AAA &rhs)
{
this->x = rhs.x;
this->y = rhs.y;
this->z = rhs.z;
return *this;
}
int AAA::operator==(const AAA &rhs) const
{
if( this->x != rhs.x) return 0;
if( this->y != rhs.y) return 0;
if( this->z != rhs.z) return 0;
return 1;
}
int AAA::operator<(const AAA &rhs) const
{
if( this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;
if( this->x == rhs.x && this->y < rhs.y) return 1;
if( this->x < rhs.x ) return 1;
return 0;
}
main()
{
map<string, AAA> M;
AAA Ablob ;
Ablob.x=7;
Ablob.y=2;
Ablob.z=4.2355;
M["A"] = Ablob;
Ablob.x=5;
M["B"] = Ablob;
Ablob.z=3.2355;
M["C"] = Ablob;
Ablob.x=3;
Ablob.y=7;
Ablob.z=7.2355;
M["D"] = Ablob;
for( map<string, AAA>::iterator ii=M.begin(); ii!=M.end(); ++ii)
{
cout << (*ii).first << ": " << (*ii).second << endl;
}
return 0;
}
#包括
#包括
使用名称空间std;
AAA级
{
friend ostream&operatorx cout它们不是重载,它们是运算符的定义。在这种特殊情况下,复制构造函数和赋值运算符执行默认的操作,因此应该忽略它们。比较运算符应该返回bool
,而不是int
,如果AAA是那么,<比较运算符将如何工作?请详细说明它的工作原理?
for (auto ii = M.begin(); ii != M.end(); ++i)