想實現一個名爲包裝功能部件的專用容器的運營商[]: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