标签:重载操作符
函数的重载操作符中也有不少细节Item item1 ,item2; item1 + item2; // call method 1 operator+(item1,item2) // call method 2 // if + is operator of class item1 + item2; item1.operator+(item2);
2 重载操作符的谨记
<1> 赋值操作符,取地址操作符,逗号操作符// output.h #pragma once #include <iostream> using namespace std; class Input { public: Input(void); ~Input(void); ostream& operator <<(ostream& out); private: string str; int fun; }; // output.cpp #include "Input.h" Input::Input(void) { str = "keep move on"; fun = 1001; } Input::~Input(void) { } ostream& Input::operator<<(ostream& out) { out<<"persist on"<<fun<<endl; return out; } //main.cpp #include "Input.h" void main() { Input in; in<<cout<<"I'll always find you"<<endl; }
#pragma once #include <vector> using namespace std; class XB { public: XB(void); ~XB(void); int& operator [](const size_t index); const int& operator [](const size_t index)const; private: vector<int> data; }; //XB.cpp #include "XB.h" XB::XB(void) { data = vector<int>(5,2); } XB::~XB(void) { } int& XB::operator [](const size_t index) { return data[index]; } const int& XB::operator[](const size_t index)const { return data[index]; } //main.cpp #include "XB.h" #include <iostream> using namespace std; void main() { XB xb; cout<<xb[3]; xb[1] = 10; cout<<xb[1]; system("pause"); }
#include <iostream> using namespace std; class Tv { public: Tv(void):m_height(100),m_width(390){}; ~Tv(void){}; int func(){return m_height * m_width;} private: int m_height; int m_width; }; class TvPtr { friend class TvPtrCnt; Tv* sp; size_t use; TvPtr(Tv* p):sp(p),use(1){} ~TvPtr(){delete sp;} }; class TvPtrCnt { public: TvPtrCnt(Tv* p):ptr(new TvPtr(p)){} TvPtrCnt(const TvPtrCnt& orig):ptr(orig.ptr){++ptr->use;}; TvPtrCnt& operator =(const TvPtrCnt &orig){++ptr->use;} ~TvPtrCnt(){if(--ptr->use ==0) delete ptr;} Tv& operator*(){return *ptr->sp;} Tv* operator->(){return ptr->sp;} const Tv& operator*()const{return *ptr->sp;} const Tv* operator->()const{return ptr->sp;} private: TvPtr* ptr; }; void main() { Tv *p = new Tv(); TvPtrCnt zp(p); std::cout<<(*zp).func()<<std::endl; std::cout<<zp->func()<<std::endl; system("pause"); }
XXX& operator++(); XXX& operator--();<2>postfix
XXX operator++(int); XXX operator--(int);注意:后自增,后自减的返回值不是引用,因为返回的是一个临时的变量
XXX.operator++(); //prefix XXX.operator++(0); //postfix
12 调用操作符和函数对象
<1>#include <iostream> using namespace std; class Abs { public: Abs(){} ~Abs(){} int operator ()(int val){return val <0 ? -val : val;} }; void main() { Abs XX; cout<<XX(-108)<<endl; system("pause"); }
标签:重载操作符
原文地址:http://blog.csdn.net/ddupd/article/details/38001567