2015-10-15 45 views
-1

想實現一個名爲包裝功能部件的專用容器的運營商[]:Shape& move_up(int index),將訪問和修改的vector<T*> v 元素,在派生類中,命名爲:class Group包裝在派生類

我試圖通過包裝基類的T& operator[](int i) { return *v[i]; }做到這一點:

Group.h

// class Group is a container of Shapes 
class Group: public Graph_lib::Vector_ref<Shape>{ 
public: 
    // constructors 
    Group::Group() 
    : upperLeft(0, 0), gridSideX(50), gridSideY(50), gridRowNumber(5), gridColumnNumber(5) 
    { 
    // create grid 
    for (size_t i = 0; i <= gridRowNumber; ++i){ 
     for (size_t j = 0; j <= gridColumnNumber; ++j){ 
       Graph_lib::Rectangle* rec = new Graph_lib::Rectangle(Point(upperLeft.x + gridSideX * j, upperLeft.y + gridSideY * i), gridSideX, gridSideY); 
       rec->set_fill_color(((i + j) % 2 == 0) ? Color::black : Color::white); 
       push_back(rec); 
     } 
    } 
    } 

    Shape& move_up(int i) { return operator[](i).move(0, 70); } 
private: 
    Point upperLeft; 
    int gridSideX; 
    int gridSideY; 
    int gridRowNumber; 
    int gridColumnNumber; 
}; 

main.cpp

#include <iostream> 
#include <vector> 
#include "Graph.h" 
#include "Simple_window.h" 
#include "Group.h" 

int main(){ 
    // define a window 
    Point tl(x_max()/2,0); 
    int width = 700; 
    int height = 700; 
    string label = "class Group"; 
    Simple_window sw(tl, width, height, label); 

    // instantiate a class Group object 
    Group gr(); 
    for (size_t i = 0; i < gr.size(); ++i) sw.attach(gr[i]); 
    sw.wait_for_button(); 
} 

目前的包裝功能是越來越紅色下劃線,當懸停在上面時,會顯示以下消息:

Error: initial value to reference to non-const must be an lvalue

的問題是,我無法找到在基類的向量訪問和修改的元素,因此,以下問題的正確方法:

我在做什麼錯誤?如何正確執行Shape& move_up(int index);函數?


1.應用改變載體的Shape元件的座標的函數move();

2.可以找到所有用於編譯的附加文件:herehere

+5

這是否真的與重載'operator []',或繼承,或與模板有關? '.move()'返回什麼?如果它不是引用,則不能綁定「move_up」的返回值。出示[最小測試用例](http://stackoverflow.com/help/mcve)(並且,請不要在每次看到您的問題時提示您這樣做) –

+2

看起來像'Group '從MyVector 繼承'違反了Liskov替代原則。 – TartanLlama

+0

@TartanLlama剛剛讀了原理;該類可能會以'MyVector '作爲數據成員來實現。 – Ziezi

回答

2

功能move_up()有:

  • 修改Shape的座標
  • 回報Shape&這樣,它可能是attache() d window對象,並在屏幕上顯示的新位置。

爲了做到這一點,它只是需要被分離成兩條線,其中第一線修改Shape對象和所述第二線通過引用返回它:

Shape& move_up(int i) { 
    operator[](i).move(0, 70); 
    return operator[](i); 
} 

或由molbdnilo建議:

Shape& move_up(int i) { 
    auto& el = (*this)[i]; 
    el.move(0, 70); 
    return el; 
} 
+2

或'(* this)[i]',這是不那麼嘈雜。 – molbdnilo

2

你的功能move()回報void

virtual void move(int dx, int dy); 

怎麼做,那麼你希望當您嘗試讓你的move_up()回到move()結果:

return <something>.move(0, 70); 

特別是你曾告訴move_up()應該返回的編譯器Shape&