如何重载下标运算符以允许一组RPG字符?

时间:2013-04-27 20:35:21

标签: c++ operator-overloading

尝试重载我的下标操作符,这样我就可以为我的游戏制作一个字符数组。无法搞清楚这个大创意。我想只是传递一个整数(即索引)并让它返回调用对象的名称(即字符本身)

下标运算符

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

1 个答案:

答案 0 :(得分:2)

你在混淆事情!如果重载Character::operator[],则表示您希望能够将Character对象视为数组。也就是说,你会这样做:

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

但那不是你想要的。相反,你只需要一个Character的数组。您根本不需要重载operator[],只需声明一个数组:

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