我有以下類:
class Character
{
/不重要的代碼
}
class Fighter : public Character
{
/不重要的代碼
}
class Healer: public Characters
{
/不重要的代碼
}
class Game: public Character { /important code }
{
public:
void move(constGridPoint & src_coordinates, const GridPoint & dst_coordinates)。
//there are more things here ,but they're not important for the sake of this question.
private。
int高度。
int width;
std::vector<std::shared_ptr<Character>> gameboard。
};
void move(const GridPoint & src_coordinates, const GridPoint & dst_coordinates)
{
for (std::vector<std::shared_ptr<Character>>:iterator i = gameboard.begin(); i !=
gameboard.end() ; i )
{
if ( (*gameboard[i]) .coordinates == src_coordinates)
{
//我是否需要實作我自己的[]運算子?
}
}
}
我試圖在我的游戲板上進行迭代,將角色從src_coordinates移動到dst_coordinates。角色也是一個被其他幾個類所繼承的類。
當我試圖訪問gameboard[i]的元素時,我得到了以下錯誤 :
不匹配 for 'operator[] (operand types are 'std: :vector<std::shared_ptr<Character> >'和'std: :vector<std::shared_ptr<Character>>:iterator' {aka '__gnu_cxx: :__normal_iterator<std::shared_ptr<Character>*, std::vector<std::shared_ptr<Character> > >'}。
這是否意味著我必須實作我自己的operator[]和operator*,因為Character是我自己的一個類? 我怎樣才能解決我的問題?
uj5u.com熱心網友回復:
迭代器是指標的一種概括。你用*從一個指標中獲得被指向的東西;你用*獲得一個迭代器當前 "指向 "的容器的元素。迭代器型別使用了運算子多載,因此它可以表現得像一個指標,即使底層容器不是一個簡單的陣列。
std::vector<std::shared_ptr<Character>>:iterator
這意味著:"一個東西,當你對它應用*時,給你一個std::shared_ptr<Character>,它來自一個std::vector<std::shared_ptr<Character>(在其他有用的屬性之中)"。
每通過一次回圈,*i都是向量中的std::shared_ptr<Character>之一。因此,(*i)->坐標是shared_ptr指向的字符的坐標。(注意->,因為我們還必須解除對shared_ptr的參考。)
與'operator[]不匹配
發生這種情況是因為你試圖把迭代器當作索引來使用。你可以通過下面的代碼清楚地看到問題所在:
char[] example = "hello, world
"。
char* ptr = &example[0] 。
example[ptr]; // wait, what?
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/314156.html
標籤:
上一篇:如果arr是一個ints陣列,arr和&arr之間的區別
下一篇:使用矢量時,[]運算子的問題
