http://www.jb51.net/article/78436.htm
函数调用
使用括号调用的函数调用运算符是二元运算符。
语法
1 | primary-expression ( expression-list ) |
备注
在此上下文中,primary-expression 为第一个操作数,并且 expression-list(可能为参数的空列表)为第二个操作数。函数调用运算符用于需要大量参数的操作。这之所以有效,是因为 expression-list 是列表而非单一操作数。函数调用运算符必须是非静态成员函数。
函数调用运算符在重载时不会修改函数的调用方式;相反,它会在运算符应用于给定类的类型的对象时修改解释该运算符的方式。例如,以下代码通常没有意义:
1 2 | Point pt; pt( 3, 2 ); |
但是,如果存在一个适当的重载函数调用运算符,则此语法可用于将 x 坐标偏移 3 个单位并将 y 坐标偏移 2 个单位。下面的代码显示了这样的定义:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // function_call.cpp class Point { public :
Point() { _x = _y = 0; }
Point &operator()( int dx, int dy )
{ _x += dx; _y += dy; return * this ; } private :
int _x, _y; }; int main() {
Point pt;
pt( 3, 2 ); } |
请注意,函数调用运算符适用于对象的名称,而不是函数的名称。
也可以使用指向函数的指针(而非该函数本身)重载函数调用运算符。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | typedef void (*ptf)(); void func() { } struct S {
operator ptf()
{
return func;
} }; int main() {
S s;
s(); //operates as s.operator ptf()() } |
下标
下标运算符 ([ ])(如函数调用运算符)被视为二元运算符。下标运算符必须是采用单个参数的非静态成员函数。此参数可以是任何类型,并指定所需的数组下标。
以下示例演示如何创建用于实现边界检查的 int 类型的矢量:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | // subscripting.cpp // compile with: /EHsc #include <iostream> using namespace std; class IntVector { public :
IntVector( int cElements );
~IntVector() { delete [] _iElements; }
int & operator[]( int nSubscript ); private :
int *_iElements;
int _iUpperBound; }; // Construct an IntVector. IntVector::IntVector( int cElements ) {
_iElements = new int [cElements];
_iUpperBound = cElements; } // Subscript operator for IntVector. int & IntVector::operator[]( int nSubscript ) {
static int iErr = -1;
if ( nSubscript >= 0 && nSubscript < _iUpperBound )
return _iElements[nSubscript];
else {
clog << "Array bounds violation." << endl;
return iErr;
} } // Test the IntVector class. int main() {
IntVector v( 10 );
int i;
for ( i = 0; i <= 10; ++i )
v[i] = i;
v[3] = v[9];
for ( i = 0; i <= 10; ++i )
cout << "Element: [" << i << "] = " << v[i] << endl; } Array bounds violation. Element: [0] = 0 Element: [1] = 1 Element: [2] = 2 Element: [3] = 9 Element: [4] = 4 Element: [5] = 5 Element: [6] = 6 Element: [7] = 7 Element: [8] = 8 Element: [9] = 9 Array bounds violation. Element: [10] = 10 |
注释
当 i 在前一个程序中达到 10 时,operator[] 将检测是否在使用超出边界的下标并发出错误消息。
请注意,函数 operator[] 将返回引用类型。这会使它成为左值,从而使您可以在赋值运算符的任何一侧使用下标表达式。
成员访问
类成员访问可通过重载成员访问运算符 (–>) 来控制。此运算符被视为此用法中的一元运算符,而重载运算符函数必须是类成员函数。因此,此类函数的声明是:
语法
1 | class -type *operator–>() |
备注
其中,class-type 是此运算符所属的类的名称。成员访问运算符函数必须是非静态成员函数。
此运算符(通常与指针取消引用运算符一起使用)用于实现在取消引用用法或对用法计数前验证指针的“智能指针”。
无法重载 . 成员访问运算符。