2015-10-15 46 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&