string可以作为key值是因为string重载了<
2.如果不重载<会提示如下错误:

3.重载<但是没有实现会提示如下错误:

#include <map>
using namespace std;
// 重载<的类或结构才能作为map的key值
class C
{
public:
int i;
string str;
bool operator < ( const C &c) const
{
return i < c.i;
}
};
void main()
{
map<C, int> mapC;
C c0;
c0.i = 0;
c0.str = " str1 ";
mapC.insert(pair<C, int>(c0, 0));
C c1;
c1.i = 1;
c1.str = " str2 ";
mapC.insert(pair<C, int>(c1, 1));
if(c0 < c1)
int iVal = mapC[c1];
// string可以作为map的key,因为重载了<
string str1 = " str1 ",str2 = " str2 ";
if(str1 < str2) // "str2"是大于"str1"的
{
int n = 0;
}
}
/* 如果不重载<会提示如下错误:
* error C2676: 二进制“<”: “const C”不定义该运算符或到预定义运算符可接收的类型的转换
* 重载<但是没有实现会提示如下错误:
* Expression: invalid operator<
* 比如bool operator < (const C &c) const{return true;}
*/
补充: C++运算符重载
运算符重载的基础就是运算符重载函数。所以今天主要讲的是运算符重载函数。
1.运算符重载是对已有的运算符赋予多重含义,使同一个运算符作用域不同类型的数据导致不同行为的发生。比如
1 int i;
2 int i1=10,i2=10;
3 i=i1+i2;
4 std::cout<<"i1+i2="<<i<<std::endl;
5
6 double d;
7 double d1=20,d2=20;
8 d=d1+d2;
9 std::cout<<"d1+d2="<<d<<std::endl;
在这个程序里"+"既完成两个整形数的加法运算,又完成了双精度型的加法运算。为什么同一个运算符"+"可以用于完成不同类型的数据的加法运算?这是因为C++针对预定义基本数据类型已经对"+"运算符做了适当的重载。在编译程序编译不同类型数据的加法表达式时,会自动调用相应类型的加法运算符重载函数。但是C++中所提供的预定义的基本数据类型毕竟是有限的,在解决一些实际的问题时,往往需要用户自定义数据类型。比如高中数学里所提到的复数:
1 class Complex //复数类
2 {
3 public:
4 double real;//实数
5 double imag;//虚数
6 Complex(double real=0,double imag=0)
7 {
8 this->real=real;
9 this->imag=imag;
10 }
11 }
假如我们建立两个复数,并用"+"运算符让它们直接相加:
1 Complex com1(10,10),com2(20,20),sum;
2 sum=com1+com2;
那么会提示没有与这些操作数匹配的 "+" 运算符的错误。这是因为Complex类类型不是预定义类型,系统没用对该类型的数据进行加法运算符函数的重载。C++就为运算符重载提供了一种方法,即运算符重载函数。其函数名字规定为operator后紧跟重载运算符。比如:operator+(),operator*()等。现在我们给上述程序声明一个加法运算符的重载函数用于完成复数的加法运算:

1 #include "stdafx.h"
2 #include <iostream>
3
4 class Complex //复数类
5 {
6 public:
7 double real;//实数
8 double imag;//虚数
9 Complex(double real=0,double imag=0)
10 {
11 this->real=real;
12 this->imag=imag;
13 }
14 };
15
16 Complex operator+(Complex com1,Complex com2)//运算符重载函数
17 {
18 return Complex(com1.real+com2.real,com1.imag+com2.imag);
19 }
20
21 int main()
22 {
23 Complex com1(10,10),com2(