2012-10-30 18 views
0

我有這樣的父類調用調用排序上主要針對不同的子類值

Shape (ShapeTwoD.cpp) 

他得到了2子類

1 is Rectangle (Rectangle.cpp) 
1 is Square (Square.cpp) 

有這個變量呼區域的聲明在矩形&廣場,但不在形狀(父)

所以我試圖按面積上升排序,但區域可以通過訪問

class->getArea(); 


vector<ShapeTwoD*> myVector; 

//記錄數據期間像寬度,高度到形狀。

myVector[arrayCount] = new Rectangle(); 
myVector[arrayCount].setWidth(inWidth); 
myVector[arrayCount].setHeight(inHeight); 
myVector[arrayCount].computeArea(); 

arrayCount ++;

//done record width , height and then compute area of the shape 

假設myVector現在包含約2矩形和1廣場

現在我想按面積升序排序它們。

但我的getArea()函數只能在子類中使用。

如果我嘗試這樣做

sort(myVector.begin(),myVector.end(),funcAreaSort); 

我不知道在哪裏創建funcAreaSort,接下來就是怎樣在孩子地區發送,假設如果他們是相同的形狀類(針對矩形矩形)或不同的形狀類(對形狀矩形)

我如何創建一個布爾操作符重載可以通過的getArea(比較),然後看哪個是更好的回報a.getArea()> b.getArea()和排序myVector

問題是在哪裏我是否創造了我認爲的那些功能? ING使得它在main.cpp中自由方法,但我不得到的那種事,並與像預選賽錯誤錯誤編譯

error: passing 'const shapeTwoD' as 'this' argument of 'virtual double shapeTwoD::getArea()' discards qualifers. 
error: passing 'const shapeTwoD' as 'this' argument of 'virtual double shapeTwoD::getArea()' discards qualifers. 
+1

從你的帖子中很難理解,但錯誤可能是告訴你'getArea()'需要是一個'const'方法。該錯誤也與您所說的內容不兼容。 – juanchopanza

+0

'myVector.computeArea();'如何編譯?那是一個'std :: vector'嗎?如果是這樣,它沒有'computeArea'方法... – Kiril

+0

@Lirik,我只是把computeArea作爲它的一個函數在child下,我運行它到setArea。目的是爲了顯示myVector [arrayCount] – user1777711

回答

1

1)充分利用比較功能採取ShapeTwoD*作爲參數,並有在virtualgetArea方法基類,你在孩子中覆蓋。

2)請方法getAreaconst

int getArea() const; 

,因爲它在邏輯上是有道理的&,這樣就可以調用它const對象。

+0

我曾嘗試使getArea()變成double,但我的compareArea函數應如何編碼。將有更多的信息。嘗試了幾個小時,但仍然無法完成排序。 – user1777711

相關問題