2011-04-28 72 views
1

我正在读一本关于C++操作符重载和我遇到下面的代码:C++操作符重载 - 查询

class Array { 
    ... 
    public:   
    Array & operator << (int x) { 
      // insert x at the end of the array 
    } 
}; 

下一页它说:该窗体的超载a << x << y << z ; 无线本地环路不行

所以它建议第二次调用被视为:
((a << x)<< y ) << z。所以它建议使用return * this;
但我没有得到如何返回*这功能在这里?请帮忙!
这里是整个代码:

#include <iostream> 
#include <cstdlib> 
using namespace std; 

class Array { 

int *a; 
int capacity; 
int size; 
int incr; 

public: 
    Array (int c=10) { 
     a = new int[c]; 
     capacity = c; 
     for (int i=0; i<c; i++) a[i]=0; 
     size=0; 
     incr = c; 
    } 
    Array &operator << (int x) { 
     if(size<capacity) a[size++] = x; 
     else { 
      int *tmp = new int [capacity+incr]; 
      for (int i=0; i<size; i++) tmp[i]=a[i]; 
      delete[] a; 
      a = tmp; 
      a[size++]=x; 
      capacity = capacity+incr; 
     } 
     return *this; 

    }; 
    int operator [] (int i) { 
     if(i<size) return a[i]; 
    }; 


}; 



int main (int argc, char *argv[]) { 

int s = atoi (argv[1]); 
Array A (s); 
for (int i=0; i<s; i++) A << i << i+1; 
for (int i=0; i<s; i++) cout << A[i] << endl; 


} 
+0

请使用四个空格缩进来格式化您的代码。请参阅http://stackoverflow.com/editing-help – SLaks 2011-04-28 17:49:49

+0

我会照顾这在未来,感谢伙计 – 2011-04-28 17:50:36

+0

我认为它应该是'数组&运算符<<'而不是'运营商<<' – 2011-04-28 17:51:38

回答

4

这真的和操作符重载无关。它被称为链接,使用常规成员函数更容易解释。假设你定义了一个名为insert这样的成员函数:

Array& insert(int x) { 
    // insert x at the end of the array 
    return *this; 
} 

return *this将参考返回到当前对象,以便您可以链的调用是这样的:

Array a; 
a.insert(0).insert(1).insert(2); 

基本上是等价于:

Array a; 
a.insert(0); 
a.insert(1); 
a.insert(2); 

insert()每次调用将返回原对象的引用,使其他调用到b e使用返回的参考进行制作。你可以重载< <运营商做同样的事情:

Array& operator<<(int x) { 
    // insert x at the end of the array 
    return *this; 
} 

现在,你可以调用链是这样的:

Array a; 
a << 0 << 1 << 2; 
+0

非常感谢:) :) – 2011-04-28 18:06:48

2

您可能因为Array &operator <<的间距越来越糊涂。函数的返回值是Array&,对数组对象的引用。

下面是一个例子。在您的电话A << i << i+1中,首先调用A << i,并返回对更新的A的引用。接下来A << i+1被称为新的参考。

+0

所以*这样做到底是什么? – 2011-04-28 17:56:35

1

是一切都确定了你的代码。你的语义中的operator <<将返回参考调用它的同一个对象。你可以看到的std::ostreamoperator >>std::istream