标签:space 封装 lin pac data 重载 ref lib color
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; class Operat { float x; float y; public: Operat(float _x = 0,float _y = 0) { x = _x; y = _y; } Operat(Operat& that) { x = that.x; y = that.y; } /* Operat operator + (Operat& that) //成员函数+重载 { Operat t; t.x = x + that.x; t.y = y + that.y; return t; } Operat& operator ++ (void)//成员函数前++重载 { x++; y++; return *this; } Operat operator ++ (int)//成员函数后++重载 { Operat t(*this); t.x++; t.y++; return t; }*/ Operat& operator [] (int i)//成员函数[]重载 { return *(this+i); } Operat& operator -> (void)//成员函数->重载 { return *this; }
void show()
{
printf("x=%f,y=%f\n",x,y);
}
//注意:普通函数 在类里加上friend声明成类的友元以后 就可以使用类的成员变量,不然成员变量一般式封装在类里的。外面函数是无法使用的
friend Operat operator + (Operat& a,Operat& b); //声明友员函数 ,这样外部函数就可以访问类的成员变量 friend Operat& operator ++ (Operat& a); friend Operat operator ++ (Operat& a,int); friend ostream& operator << (ostream& os,Operat& p); friend istream& operator >> (istream& is,Operat& p); ~Operat(){} }; void* operator new (unsigned int size)//全局函数new的重载 { return malloc(size); } Operat operator + (Operat& a,Operat& b)//全局函数+的重载 { Operat t(a.x+b.x,a.y+b.y); return t; } Operat& operator ++ (Operat& a)//全局函数前++的重载 { a.x++; a.y++; return a; } Operat operator ++ (Operat& a,int)//全局函数后++的重载 { Operat t = a; a.x++; a.y++; return t; } ostream& operator << (ostream& os,Operat& p)//全局函数 << 的重载 { return os << "x=" << p.x << " " << "y=" << p.y << " "; } istream& operator >> (istream& is,Operat& p)//全局函数 >> 的重载 { return is >> p.x >> p.y; } int main() { Operat a(1,2); Operat b(3,4); (a++).show(); a.show(); cin >> a; cout << a << b << endl; }
标签:space 封装 lin pac data 重载 ref lib color
原文地址:https://www.cnblogs.com/yyb123/p/9471830.html