C++ 操作符函数
Point.h
/*
* Point.h
*
* Created on: 2014年5月22日
* Author: John
*/
#include<iostream>
using namespace std;
#ifndef POINT_H_
#define POINT_H_
class Point {
private:
int x;
int y;
public:
Point(int x, int y){set(x,y);}
Point():Point(0,0){};
void set(int x, int y){
this->x = x;
this->y = y;
}
Point operator+(const Point &pt);//成员函数,调用该函数的对象成为全局函数
//const关键字,防止输入的参数被修改,&提供对原始数据的引用
friend Point operator-(Point pta, Point ptb); // 可以直接访问 私有属性
friend Point operator-(int n, Point ptb); // 重载操作符
//复制操作符函数
Point &operator=(const Point & src){
set(src.x,src.y);
return *this;//this是指针,对this取值,
//注意到operator前面的&符号 返回的是一个值的引用
}
//输出函数符
friend ostream &operator<<(ostream &outstream, Point &pt);
int get_x() const {return this->x;}
int get_y()const {return this->y;}
virtual ~Point();
};
#endif /* POINT_H_ */
Point.cpp
/*
* Point.cpp
*
* Created on: 2014年5月22日
* Author: John
*/
#include "Point.h"
//Point::Point(int x, int y) {
// // TODO Auto-generated constructor stub
//
//}
Point::~Point() {
// TODO Auto-generated destructor stub
}
Point Point::operator +(const Point &pt){
// Point new_pt;
// new_pt.x =this->x+pt.x;
// new_pt.y = this->y+pt.y;
// return new_pt;
return Point(x+pt.x,y+pt.y); // 这行代码在Point类的内部,所以可以直接访问私有变量。
}
Test.cpp
/*
* Test.cpp
*
* Created on: 2014年5月22日
* Author: John
*/
//#include<iostream>
#include"Point.h"
//using namespace std;
//全局函数的操作符,每个操作数对应于该函数的一个输入参数。
Point operator-(Point pta, Point ptb){
//return Point(pta.get_x()-ptb.get_x(), pta.get_y() - ptb.get_y());
//为了能够直接访问私有变量,可以在Point.h文件里面做如下声明:
//friend Point operator-(Point pta, Point ptb);
return Point(pta.x-ptb.x,pta.y-ptb.y);
}
Point operator-(int n, Point ptb){
return Point(n-ptb.x,n-ptb.y);
}
ostream &operator<<(ostream &outstream, Point &pt){
outstream<<pt.x<<" , "<<pt.y;
return outstream;
}
int main(int argc, char** argv){
Point pt1;
Point pt2(1,2);
Point pt3(3,4);
cout<<"Pt1 is "<<pt1.get_x()<<", "<<pt1.get_y()<<endl;
cout<<"Pt2 is "<<pt2.get_x()<<", "<<pt2.get_y()<<endl;
cout<<"Pt3 is "<<pt3.get_x()<<", "<<pt3.get_y()<<endl;
pt1 = pt2+pt3;
cout<<"Pt1(=pt2 + pt3) is "<<pt1.get_x()<<", "<<pt1.get_y()<<endl;
Point pt4 = pt1 - pt2;//-操作数
cout<<"pt4(=Pt1 - pt2) " <<pt4.get_x()<<", "<<pt4.get_y()<<endl;
int num = 10;
cout<<"Num is "<<num<<endl;
Point pt5 = num - pt3;
//重载-操作数
cout<<"pt5=("<<num<<" - pt3) is: "<< pt5.get_x()<<", "<<pt5.get_y()<<endl;
pt5 = pt4; //赋值操作符
cout<<"pt5 = pt4 equals "<<pt5.get_x()<<", "<<pt5.get_y()<<endl;
cout<<"pt5 is "<<pt5<<endl; //这里使用了,<<输出重载符。
return 0;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。