C++重载操作符笔记

来源:互联网 发布:会员制软件 编辑:程序博客网 时间:2024/06/04 18:53

重载和多态是不一样的,重载主要作用是多操作符号的重载。(Operator overloading)

如有下面的类:

class complex { // very simplified complexdouble re, im;public:complex(double r, double i) :re{r}, im{i} { }complex operator+(complex);complex operator*(complex);};


要实现其中的+和*操作,就必须自定义其函数功能,也就是重载了编译器原有的+和*操作。

void f(complex a, complex b){complex c = a + b; // shor thandcomplex d = a.operator+(b); // explicit call}


下面操作符都是可以重载的:

 

注意其重载的参数不能出错:

class X {public: // members (with implicit this pointer):X∗ operator&(); // prefix unary & (address of)X operator&(X); // binar y & (and)X operator++(int); // postfix increment (see §19.2.4)X operator&(X,X); // error : ter naryX operator/(); // error : unar y /};X operator−(X); //prefix unary minusX operator−(X,X); //binar y minusX operator−−(X&,int); // postfix decrementX operator−(); //error : no operandX operator−(X,X,X); // error : ter naryX operator%(X); // error : unar y %

操作符= (assignment), & (address-of), and , (sequencing) 都有预先定义的意义,但是可以利用deleted关键字去掉:

class X {public:// ...void operator=(const X&) = delete;void operator&() = delete;void operator,(const X&) = delete;// ...};void f(X a, X b){a = b; // error : no operator=()&a; // error : no operator&()a,b; // error : no operator,()}

 

操作符的重载参数必须有一个是用户自定义的数据类型,这样就保证了不可以修改原有操作符的作用。

日期数据类型重载++:

enum Day { sun, mon, tue, wed, thu, fri, sat };Day& operator++(Day& d){return d = (sat==d) ? sun : static_cast<Day>(d+1);}


如果是自定义的类,成员多,占内存大,那么就定义move operation会让传输速度加快。

Matrix operator+(const Matrix& a, const Matrix& b) // return-by-value{Matrix res {a};return res+=b;}

操作符如果是返回参数的其中一个对象的就通常是返回引用参数:

Matrix& Matrix::operator+=(const Matrix& a) // return-by-reference{if (dim[0]!=a.dim[0] || dim[1]!=a.dim[1])throw std::exception("bad Matrix += argument");double∗ p = elem;double∗ q = a.elem;double∗ end = p+dim[0]∗dim[1];while(p!=end)∗p++ += ∗q++return ∗this;}

单操作符!例子。

X operator!(X);struct Z {Z operator!(); //does not hide ::operator!()X f(X x) { /* ... */ return !x; } // invoke ::operator!(X)int f(int x) { /* ... */ return !x; } // invoke the built-in ! for ints};