C++中特殊運算符的重載
阿新 • • 發佈:2018-08-14
++ 使用 註意 運算 全局 stdio.h printf com link
#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; }
C++中特殊運算符的重載