Trying to overload my subscript operator, so I can make an array of characters for my game. Having trouble figuring out the big idea. I was thinking of just passing it an integer (ie for the index) and having it return the name of the invoking object(ie the character itself)
subscript operator
Character * Character::&operator[](int index)
{
return this->mName[index];
}
The error I am getting is:
Error: a reference type of "Character*&" (not const-qualified) cannot be
initialized with a value type of char.
Btw, I am using my own string class -- which I wrote myself (ie this is school after all) -- so I can overload anything if necessary.
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
You're confusing things! If you overload Character::operator[]
, that means you want to be able to treat a Character
object like an array. That is, you would do:
Character c("Bob", pouch, purse);
c[0]; // Using the Character like an array
But that's not what you want. Instead you just want an array of Character
s. You don't need to overload operator[]
to do that at all, you just declare an array:
Character array[10]; // This is an array of Characters
array[0].setName("Bob"); // This sets the 0th Character's name to Bob
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.