操作符重载
type operator sign (parameters) { /*...*/ }
能重载的操作符列表sign table
+ - * / = < > += -= *= /= << >> <<= >>= == != <= >= ++ -- % & ^ ! | ~ &= ^= |= && || %= [] () , ->* -> new delete new[] delete[]
操作符的使用(语句调用)
Expression | Operator | Member function | Global function |
---|---|---|---|
@a | + - * & ! ~ ++ -- | A::operator@() | operator@(A) |
a@ | ++ -- | A::operator@(int) | operator@(A,int) |
a@b | + - * / % ^ & | < > == != <= >= << >> && || , | A::operator@ (B) | operator@(A,B) |
a@b | = += -= *= /= %= ^= &= |= <<= >>= [] | A::operator@ (B) | - |
a(b, c...) | () | A::operator() (B, C...) | - |
a->x | -> | A::operator->() | - |
// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
关键字this
静态成员
Static members
// static members in classes
#include <iostream>
using namespace std;
class CDummy {
public:
static int n;
CDummy () { n++; };
~CDummy () { n--; };
};
int CDummy::n=0;
int main () {
CDummy a;
CDummy b[5];
CDummy * c = new CDummy;
cout << a.n << endl;
delete c;
cout << CDummy::n << endl;
return 0;
}
using namespace std;
struct A
{
int value;
A(int v){value = v;};
A& operator++()
{
value+=10;
return *this;
}
const A operator++(int)
{
A temp = *this;
value+=20;
return temp;
}
};
int main() {
A a(1);
a++;
cout << a.value << endl;
++a;
cout << a.value << endl;
return 0;
}
- Success time: 0 memory: 3296 signal:0
21 31
附录:前自增和后自增的差别
http://blog.csdn.net/cuglij/article/details/2913282
前自增和后自增运算符++的重载
很久以前(八十年代),没有办法区分++和--操作符的前缀与后缀调用。这个问题遭到程序员的报怨,于是C++语言得到了扩展,允许重载increment 和 decrement操作符的两种形式。 然而有一个句法上的问题,重载函数间的区别决定于它们的参数类型上的差异,但是不论是increment或decrement的前缀还是后缀都只有一个参数。为了解决这个语言问题,C++规定后缀形式有一个int类型参数,当函数被调用时,编译器传递一个0做为int参数的值给该函数。
increment的前缀形式表示“增加然后取回”,后缀形式表示“取回然后增加”。
- #include "stdafx.h"
- #include "assert.h"
- class A
- {
- public:
- A(int i)
- :m_i(i)
- {
- }
- // ++i
- A& operator++()
- {
- ++m_i;
- return *this;
- }
- // i++
- const A operator++(int)
- {
- A tmp = *this;
- ++(*this); // Implemented by prefix increment
- return A(tmp);
- }
- int m_i;
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- int i = 0;
- int i1 = i++; // i1 = 0; i = 1;
- int i2 = ++i; // i2 = 2; i = 1;
- A a(0);
- A a1 = a++; // i1 = 0; i = 1;
- A a2 = ++a; // i2 = 2; i = 1;
- //a++++; //avoid
- //++++a; //support
- assert(i1 == a1.m_i);
- assert(i2 == a2.m_i);
- return 0;
- }
说明
1. 类中的++操作符号重载之后必须保证其语意与全局++相同。
2.为了区分前后,用++()表示前自增,用++(int)后自增。
3.因为按照前自增的标准定义,应该支持"++++a"的语法,而且两次前自增都应该是对a对象的自身操作,如果返回A类型,那第二次前自增调用的是临时对象的前自增操作。
4.后自增应该返回"const Complex".这可以防止形如"a++++"的用法。
5.一般通过前自增操作来实现后自增操作符函数。
参考
C++ articles:Guru of the Week #4 -- Class Mechantics
More Effective C++