I am trying to implement a wrapping function named: Shape& move_up(int index)
, that will access and modify1 elements of vector<T*> v
, in the derived class, named: class Group
.
I am trying to do that by wrapping the T& operator[](int i) { return *v[i]; }
of the base class:
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();
}
Currently the wrapping function is getting underlined in red, when hover above it displays the following message:
Error: initial value to reference to non-const must be an lvalue
The problem is that I can't find a right way of accessing and modifying the elements in the vector of the base class, thus the following question:
What am I doing wrong? How to correctly implement the Shape& move_up(int index);
function?
1. Apply the function move();
that changes the coordinates of a Shape
element of the vector.
2. All the additional files for compilation could be found: here and here.