2010-02-07 28 views
3

問題與運營商[]在C++中,我有一些類:C++運算符[]重載的問題(工作正常,但不是爲指針,爲什麼?)

197 class Permutation{ 
198   private: 
199     unsigned int* array; 
200     unsigned int size; 
201 
202     void fill(){ 
203       for(unsigned int i=0;i<size;i++) 
204         array[i]=i; 
205     } 
206     void init(const unsigned int s){ 
207       if(s){ 
208         array=new unsigned int[s]; 
209         size=s; 
210       }else{ 
211         size=0; 
212         array=0; 
213       } 
214     } 
215     void clear(){ 
216       if(array){ 
217         delete[]array; 
218         array=0; 
219       } 
220       size=0; 
221     } 
222   public: 
223     Permutation(const unsigned int& s=0):array(0),size(0){ 
224       init(s); 
225       fill(); 
226     } 
227     ~Permutation(){ 
228       clear(); 
229     } 
230     unsigned int& operator[](const unsigned int& idx){ 
231       assert(idx<size); 
232       return array[idx]; 
233     } 
234     unsigned int& get(const unsigned int& idx) 
235     { 
236       assert(idx<size); 
237       return array[idx]; 
238     } 


253     Permutation& operator=(const Permutation& p){ 
254       clear(); 
255       init(p.size); 
256       size=p.size; 
257       for(unsigned int i=0;i<size;i++) 
258         array[i]=p.array[i]; 
259       return *this; 
260     } 
261 
262     Permutation(const Permutation&p) 
263     { 
264       clear(); 
265       init(p.size); 
266       size=p.size; 
267       for(unsigned int i=0;i<size;i++) 
268         array[i]=p.array[i]; 
269     } 
}; 

當我使用

Permutation x(3); 
x[0]=1; 

它工作得很好,但是當我使用:

Permutation* x=new Permutation(3); 
x->get(0)=10; // this works fine 
x[0]=1; 

在這種情況下,調試器,我看到它被稱爲新的對象爲置換類的構造函數,什麼 正在進行 ?爲什麼? 我有人知道發生了什麼,我會感謝信息。

回答

6

首先,你的代碼:

Permutation* x=new Permutation(3); 
x->get(0)=10; // this works fine 

然後你這樣做:

x[0]=1; 

和你正在做的是治療指針x作爲數組,並初始化它,這是手寫爲:

x[0] = Permuation(1); // implicit conversion using Permulation(const unsigned long&) 

你的意思寫的是:

(*x)[0]=1; // follow x and then invoke the [] operator 

或者,等效:

x->operator[](0) = 1; 
+0

謝謝你的回答!這是更優雅的方式來調用(* x)[0] = 1,或者它是最漂亮的? – Tomek 2010-02-07 21:08:44

+0

@Tomek:增加了一個替代形式;雖然對這兩個選項的相對漂亮沒有任何意見:) – Will 2010-02-07 21:27:43

+0

http://www.gotw.ca/publications/c_family_interview.htm在一次採訪中,Stroustrup說他考慮添加一個像'x - > [0]這樣的語法'語言,但它沒有成功。 – ephemient 2010-02-07 22:08:29

2

對於指針,x[0]相當於*(x+0),這相當於*x。所以你實際上分配給Permutation對象。

由於您正在分配值1,因此使用Permutation(const unsigned int&)轉換構造函數。這會創建一個Permutation類型的臨時文件,然後使用您的賦值運算符將其複製到對象*x中。

0

我想介紹一下其他選項,以便您更輕鬆地編寫此代碼。如果你在一個地方使用重載運算符

Permutation &rx = *x; 
rx[0] = 1; // same as (*x)[0] = 1; 

,這是矯枉過正:與其與指針的工作,你可以創建一個參考。但是當你在很多地方使用重載操作符時,我發現這個技巧非常方便。

+0

thx。非常棘手:) – Tomek 2010-02-07 23:28:35