想实现一个名为包装功能部件的专用容器的运营商[]: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();
。
这是否真的与重载'operator []',或继承,或与模板有关? '.move()'返回什么?如果它不是引用,则不能绑定“move_up”的返回值。出示[最小测试用例](http://stackoverflow.com/help/mcve)(并且,请不要在每次看到您的问题时提示您这样做) –
看起来像'Group '从MyVector继承'违反了Liskov替代原则。 –
TartanLlama
@TartanLlama刚刚读了原理;该类可能会以'MyVector'作为数据成员来实现。 –
Ziezi