重载和多态是不一样的,重载主要作用是多操作符号的重载。(Operator overloading)
如有下面的类:
[cpp] view plaincopyprint?
class complex { // very simplified complex
double re, im;
public:
complex(double r, double i) :re{r}, im{i} { }
complex operator+(complex);
complex operator*(complex);
};
要实现其中的+和*操作,就必须自定义其函数功能,也就是重载了编译器原有的+和*操作。
[cpp] view plaincopyprint?
void f(complex a, complex b)
{
complex c = a + b; // shor thand
complex d = a.operator+(b); // explicit call
}
下面操作符都是可以重载的:
注意其重载的参数不能出错:
[cpp] view plaincopyprint?
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 nary
X operator/(); // error : unar y /
};
X operator?(X); //prefix unary minus
X operator?(X,X); //binar y minus
X operator??(X&,int); // postfix decrement
X operator?(); //error : no operand
X operator?(X,X,X); // error : ter nary
X operator%(X); // error : unar y %
操作符= (assignment), & (address-of), and , (sequencing) 都有预先定义的意义,但是可以利用deleted关键字去掉:
[cpp] view plaincopyprint?
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,()
}
操作符的重载参数必须有一个是用户自定义的数据类型,这样就保证了不可以修改原有操作符的作用。
日期数据类型重载++:
[cpp] view plaincopyprint?
enum Day { sun, mon, tue, wed, thu, fri, sat };
Day& operator++(Day& d)
{
return d = (sat==d) ? sun : static_cast(d+1);
}
如果是自定义的类,成员多,占内存大,那么就定义move operation会让传输速度加快。
[cpp] view plaincopyprint?
Matrix operator+(const Matrix& a, const Matrix& b) // return-by-value
{
Matrix res {a};
return res+=b;
}
操作符如果是返回参数的其中一个对象的就通常是返回引用参数:
[cpp] view plaincopyprint?
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;
}
单操作符!例子。
[cpp] view plaincopyprint?
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
};
阅读(448) | 评论(0) | 转发(0) |