2013-04-27 55 views
0

試圖超載我的下標操作符,所以我可以爲我的遊戲製作一組字符。無法弄清楚這個大想法。我想的只是傳遞一個整數(即該指數),並讓它返回調用對象的名稱(即字符本身)如何重載下標運算符以允許RPG字符數組?

下標操作

Character * Character::&operator[](int index) 
{ 
    return this->mName[index]; 
} 

我的錯誤得到的是:

Error: a reference type of "Character*&" (not const-qualified) cannot be 
initialized with a value type of char. 

順便說一句,我用我自己的字符串類 - 這是我自己寫的(即這是學校畢竟) - 這樣我就可以在必要時超載什麼。

character.h

#ifndef CHARACTER_H 
#define CHARACTER_H 

#include "backpack.h" 
#include "coinpouch.h" 
#include "string.h" 

class Character 
{ 

public: 
//Default constructor 
Character(); 

//Destructor 
~Character(); 

//Constructor 
Character(const String & name, const CoinPouch & pouch, const BackPack & purse); 

//Copy Constructor 
Character(const Character & copy); 

//Overloaded assignment operator 
Character &operator=(const Character & rhs); 

//Overloaded subscript operator 
Character * &operator[](int index); 

//Setters 
void setName(String name); 
void setCoinPouch(CoinPouch pouch); 
void setBackPack(BackPack purse); 

//Getters 
String getName(); 
CoinPouch getPouch(); 
BackPack getPurse(); 

//Methods 
void Display(); 


private: 
//Data members 
String mName; 
CoinPouch mPouch; 
BackPack mPurse; 
}; 

#endif 

回答

2

你困惑的事情!如果您超載Character::operator[],那意味着您希望能夠像數組一樣處理對象Character。也就是說,你會這樣做:

Character c("Bob", pouch, purse); 
c[0]; // Using the Character like an array 

但這不是你想要的。相反,您只需要一組Character s。你根本不需要超載operator[]這麼做,你只需聲明一個數組:

Character array[10]; // This is an array of Characters 
array[0].setName("Bob"); // This sets the 0th Character's name to Bob 
+0

該死的我很笨。謝謝你,先生! – MrPickle5 2013-04-27 20:46:44