首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >STL--MAP--添加字符串作为键,添加类对象作为值

STL--MAP--添加字符串作为键,添加类对象作为值
EN

Stack Overflow用户
提问于 2016-01-22 12:54:04
回答 1查看 111关注 0票数 0

代码解释了对映射的插入,其中键类型是字符串,值是对类对象的引用。但有3个重载函数,如overloading=运算符、overloading<运算符和重载==运算符。谁能给我解释一下为什么这里会超载?

代码语言:javascript
运行
复制
#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 &copyin)   // 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;
    }
EN

回答 1

Stack Overflow用户

发布于 2016-01-22 13:47:00

它们不是重载,它们是运算符的定义。在这种特殊情况下,复制构造函数和赋值操作符执行默认值将执行的操作,因此应省略它们。比较运算符应返回bool而不是int,这样可以更有效地编写<比较。这两个比较在给定的代码中都没有使用,因此它们也是多余的。如果AAA是映射中的关键字,那么它们将是必需的,但由于这是不需要它们的值。

顺便说一下,您可以将for循环定义为

代码语言:javascript
运行
复制
for (auto ii = M.begin(); ii != M.end(); ++i)

除非您的编译器足够老,不支持auto的这种用法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34939262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档