运算符重载
对于自定义的类型,自定义c++运算符的行为。
语法
运算符重载与函数重载一样,只是运算符有特殊的函数名。
operator op (1)
operator type (2)
operator new
operator new [] (3)
operator delete
operator delete [] (4)
重载运算符
重载运算符可以通过函数调用调用(对于非内置的操作符):
std::string str = "Hello, ";
str.operator+=("world"); // same as str += "world";
operator<<(operator<<(std::cout, str) , '\n'); // same as std::cout << str << '\n';
限制
- (::, ., .*, ?:)不能被重载
- (&&, || , ,)重载,将丢失short-circuit 和 sequence 特性
- 不能改变运算符的优先级和结合性
权威的实现
对于运算符重载,除了上面几点要求,没有其他任何限制。对于,重载运算符的返回值,不需要做任何限制。但是,由于我们希望重载的运算符的行为尽量和内置的运算符行为相似。所以,通常需要参考权威的实现方法。
赋值运算符
常规方法:
T& T::operator=(T arg) // copy/move constructor is called to construct arg
{
swap(arg); // resources are exchanged between *this and arg
return *this;
} // destructor of arg is called to release the resources formerly held by *this
但是,对于存有资源的对象,常用以下方法(减少临时变量创建消耗的资源):
T& operator=(const T& other) // copy assignment
{
if (this != &other) { // self-assignment check expected
if (/* storage cannot be reused (e.g. different sizes) */)
{
delete[] mArray; // destroy storage in this
/* reset size to zero and mArray to null, in case allocation throws */
mArray = new int[/*size*/]; // create storage in this
}
/* copy data from other's storage to this storage */
}
return *this;
}
T& operator=(T&& other) // move assignment
{
assert(this != &other); // self-assignment check not required
delete[] mArray; // delete this storage
mArray = other.mArray; // move
other.mArray = nullptr; // leave moved-from in valid state
return *this;
}
流运算符
只能作为非成员变量:
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
std::istream& operator>>(std::istream& is, T& obj)
{
// read obj from stream
if( /* T could not be constructed */ )
is.setstate(std::ios::failbit);
return is;
}
函数调用运算符
当一个自定义类,重载一个函数调用运算符operator(),它就变成一个FunctionObject类型。
struct Sum
{
int sum;
Sum() : sum(0) { }
void operator()(int n) { sum += n; }
};
Sum s = std::for_each(v.begin(), v.end(), Sum());
Increment and decrement
struct X
{
X& operator++()
{
// actual increment takes place here
return *this;
}
X operator++(int)
{
X tmp(*this); // copy
operator++(); // pre-increment
return tmp; // return old value
}
};