学了c,c++,算是基本入门了吧,以前做的好多笔记由于硬盘坏了,换了硬盘后数据都丢了,只好从c++模版篇开始了,写博客呢不仅可以加深自己的印象,更好的复习学过的知识,也有助于对知识的总结,归纳,写得不好,还请高人指点指点。好了,步入正题吧, c++中可以用直接用"+"实现字符串的连接,比如string a="hello",cout<<a+" world"<<endl;(补充一句,直接定义string a="hello "+"world"这样是错误的) 这就是运算符重载(本质就是函数重载,关键字operator),类中分为友元函数重载和成员函数重载,以简单的坐标类为例把,写法
class Coordinate{
friend Coordinate &opetator-(coordinate &coor){//需要传入参数(前置)
coor.m_iX=-coor.m_iX;
coor.m_iY=-coot.m_iY;
return *this;
}
friend Coordinate operator++(Coordinate& c,int){//后置的话operator前不加引用
Coordinate c1(c);
c.m_iX++;
c.m_iY++;
return c1;
}
# include <iostream>
using namespace std;
class Coordinate{
friend Coordinate& operator++(Coordinate &coor)//友元函数重载(全局)operator前不加引用
{
++coor.m_iX;
++coor.m_iY;
return coor;
}
public:
Coordinate(int x, int y){
m_iX = x;
m_iY = y;
}
int getX(){
return m_iX;
}
int getY(){
return m_iY;
}
Coordinate &operator-(){ //成员函数重载
m_iX = -m_iX;
m_iY = -m_iY;
return *this;
}
private:
int m_iX;
int m_iY;
};
int main(){
Coordinate c1(1,1);
-c1;
cout << c1.getX() << " " << c1.getY() << endl;
++c1;
cout << c1.getX() << " " << c1.getY() << endl;
system("pause");
return 0;
}