0

试图重载我的下标运算符,以便我可以为我的游戏制作一组字符。难以弄清楚大创意。我正在考虑只传递一个整数(即用于索引)并让它返回调用对象的名称(即字符本身)

下标运算符

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.  

顺便说一句,我正在使用我自己的字符串类——我自己编写的(即毕竟这是学校)——所以我可以在必要时重载任何东西。

字符.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
4

1 回答 1

2

你把事情搞糊涂了!如果你重载Character::operator[],这意味着你希望能够Character像数组一样对待一个对象。也就是说,你会这样做:

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

但这不是你想要的。相反,您只需要一个 s 数组Character。您根本不需要重载operator[]来执行此操作,只需声明一个数组:

Character array[10]; // This is an array of Characters
array[0].setName("Bob"); // This sets the 0th Character's name to Bob
于 2013-04-27T20:38:24.383 回答