大部分符号可以重载,except . , .* , :: , ?: , sizeof, typeid .
associativity(结合性) and precedence(优先级) of an operator cannot be changed
二元操作符可以由接受一个形参的非静态成员函数(另一个操作数是对象本身)或接受两个形参的非成员函数定义
•For operator@ : aa @ bb
means: aa.operator@(bb)
or operator@(aa,bb)
•=, [], () ,-> operators must be defined as member functions.
A user-defined operator function must be have relation with a user-defined type.
使用成员函数或非成员的特定操作符?
经验法则:
——if操作符函数固有地修改
其第一个操作数的值,使用成员。
——否则,使用非成员
No implicit user-defined conversions are applied to the left side of operator . or ->
void f(complex z)
{
3+z; // 3 è complex, operator+(complex(3),complex)
3.operator+=(z); // ERROR
3+=z; // ERROR
}
成员函数指定三个属性:
[1]函数可以访问私有成员
[2]函数在类的作用域中
[3]函数必须在对象上调用
(它有一个指针)
静态成员函数具有属性[1][2]。
友元函数只有属性[1]。友元可以访问类的所有成员,但它不属于类
友元声明可以放在类的私有部分或公共部分。
一个类的成员函数可以是另一个类的友元。
如果一个类的所有成员函数都是另一个类的友元,则可以将这个类声明为另一个类的友元类。
class List_iterator {
public:
int* next();
…
};
class List {
…
friend class List_iterator;
};
如果希望对操作的所有操作数进行隐式转换,则实现该转换的函数必须是接受常量引用形参或非引用形参的非成员函数。
如果没有定义转换,则两者都可以。
class X {
…
public:
X(int);
int m1();
int m2() const;
friend int f1(X&);
friend int f2(const X&);
friend int f3(X);
};
99.m1() or 99.m2() //error
f1(99) //error
f2(99) and f3(99) //OK
后缀操作符需要一个int形参来区别于前缀操作符。
class T {
…
void operator++(); //prefix
void operator++(int); //suffix
};
void operator--(T); //prefix
void operator--(T,int);//suffix
T a,b;
++a; //a.operator++();
a++; //a.operator++(0);
--b; //operator--(b);
b--; //operator--(b,0);