您的位置:首页 > 编程语言 > C语言/C++

C++重载运算符

2015-07-10 17:17 579 查看
本文主要介绍:结构体中重载运算符、类重载运算符以及容器排序重载运算符。

1、结构体重载运算符

typedef struct tagSaveImgFile
{
tagSaveImgFile &operator = (tagSaveImgFile &other) //放在结构体内部
{
m_scale = other.m_scale;
m_imgPath = other.m_imgPath;
m_labelPath = other.m_labelPath;
m_xmlPath = other.m_xmlPath;

return *this;

};

bool operator <(const tagNeighbor &other )
{

return m_dissimCrit<other.m_dissimCrit;
}

int m_scale;
string m_imgPath;
string m_labelPath;
string m_xmlPath;
}CSaveFiles;


2、类定义重载运算符

.h文件中类定义:

class CParameter
{
public:
CParameter();
~CParameter();

CParameter & operator = (const CParameter &other);
int m_scale;
string m_imgPath;
string m_labelPath;
string m_xmlPath;
};


.cpp中文件中程序:

CParameter::CParameter()
{

}
CParameter::~CParameter()
{

}

CParameter & CParameter::operator = (const CParameter &other)
{
if (this != &other)
{
m_scale = other.m_scale;
m_imgPath = other.m_imgPath;
m_labelPath = other.m_labelPath;
m_xmlPath = other.m_xmlPath;
}
return *this;
}




class CNeighbor
{
public:
int     m_id;
double  m_dissimCrit;
double  m_mergedPerim;

//重载等于
CNeighbor &operator = (const CNeighbor &other)
{
m_id = other.m_dissimCrit;
m_dissimCrit = other.m_dissimCrit;
m_mergedPerim = other.m_mergedPerim;
}
//重载 < 设定排序顺序
bool operator < (const CNeighbor &other) const //set容器要加const
{
return m_dissimCrit < other.m_dissimCrit;
}

//构造函数 支持CNeighbor(a,b,c)赋值
CNeighbor(int id, double dissimCrit, double mergedPerim)
{
m_id = id;
m_dissimCrit = dissimCrit;
m_mergedPerim = mergedPerim;
}
};


3、容器排序重载运算符

.h文件定义及重载:

class CParameter
{
public:
CParameter();
~CParameter();

CParameter & operator = (const CParameter &other);
int m_scale;
string m_imgPath;
string m_labelPath;
string m_xmlPath;
};

typedef list<CParameter> listParameter;

//list可对存储的对象排序,重载按m_scale升序排列,即由小到大排序
inline bool operator <(const CParameter &one, const CParameter &other)
{
return one.m_scale<other.m_scale;
}


.cpp中调用:

listParameter listpara;

CParameter para;
para.m_scale = 300;
para.m_imgPath = "C:\\Users\\hong\\Desktop\\ObjectSeg100.tif";
para.m_labelPath = "C:\\Users\\hong\\Desktop\\ObjectLabel100.tif";
para.m_xmlPath = "C:\\Users\\hong\\Desktop\\ObjectSeg.xml";

listpara.push_back(para);

CParameter other;
other.m_scale = 200;
other.m_imgPath = "C:\\Users\\hong\\Desktop\\ObjectSeg100.tif";
other.m_labelPath = "C:\\Users\\hong\\Desktop\\ObjectLabel100.tif";
other.m_xmlPath = "C:\\Users\\hong\\Desktop\\ObjectSeg.xml";

listpara.push_back(other);

cout<<listpara.begin()->m_scale<<endl; //输出结果为300

listpara.sort();

cout<<listpara.begin()->m_scale<<endl; //输出结果为200


注:

1.引用符&的介绍:

/article/7070247.html

2.引用与指针区别:

/article/4070375.html

3.值传递、指针传递和引用传递效率比较

http://blog.sina.com.cn/s/blog_a3daf09d01015c0r.html

4.const用法:

/article/2244400.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: