C++ 操作符重载
目录

C++支持操作符重载:

type operator operator-symbol ( parameter-list )

但是操作符重载有没有限制? 是不是所有操作符都能重载?

More effective C++的第七条介绍了一些不能重载的操作符:

.                .*             ::               ?:
new              delete         sizeof           typeid
static_cast      dynamic_cast   const_cast       reinterpret_cast

以及可以重载的操作符:

operator new                    operator delete
operator new[]                  operator delete[]
+     -     *     /     %     ^     &     |     ~
!     =     <     >     +=    -=    *=    /=    %=
^=    &=    |=    <<    >>    >>=   <<=   ==    !=
<=    >=    &&    ||    ++    --    ,     ->*   ->
()    []

虽然可以重载,但是这一条内容首先就建议不重载这些操作符:

  • &&: 不符合惰性求值要求
  • ||: 不符合惰性求值要求
  • ,: 不符合返回最后一个表达式要求

其它的操作符重载,我们可以看看其声明式:

// operator new
void* operator new(std::size_t size) throw(std::bad_alloc);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_constant) throw();  // no throw
void* operator new (std::size_t size, void* ptr) throw();   // placement new

// operator delete
void operator delete(void *p) throw();
void operator delete(void *p, const std::nothrow_t&) throw();
void operator delete(void *, void *) throw();

// operator new[]
void *operator new[](std::size_t size) throw(std::bad_alloc);
void *operator new[](std::size_t size, const std::nothrow_t& nothrow_constant) throw();
void *operator new[](std::size_t size, void* ptr) throw();

// operator delete[]
void operator delete[](void* p) throw();
void operator delete[](void* p, const std::nothrow_t&) throw();
void operator delete[](void *, void *) throw();

// =
C& operator=(const C& c){ ...; return *this;}

// +/-/*
const C operator+(const C &other);
friend const C operator+(const C&, const C&);

// +=/-=/*=
C& operator+=(const C& c){ ...; return *this;}

// ++/--
C& operator++();          // prefix increment
const C operator++(int);  // postfix increment

// ==/!=/</<=/>/>=
bool operator==(const C &other) const;

// &
C* operator&();
const C* operator&() const;

// <<
friend inline ostream & operator << (ostream & os, test &t1);

// >>
friend inline istream & operator >> (istream & is, test &t1);

// ()
... operator(...) ();

// []
C& operator[](int offset);                    // for changed object
const C& operator[](int offset) const;        // for constant object

操作符重载有一个规则:每个重载操作符必须获得至少一个“用户定制类型”的自变量。 因为,诸如此类的重载:

const C operator+(int l, int r);    // error

是错误的,这改变了系统默认的加法含义。

参考:

发表评论