[英]How to overload the subscript operator to allow an array of RPG characters?
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 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. 如果重载Character::operator[]
,则意味着您希望能够像处理数组一样处理Character
对象。 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. 相反,你只需要一个Character
数组。 You don't need to overload operator[]
to do that at all, you just declare an array: 您根本不需要重载operator[]
来执行此operator[]
,只需声明一个数组:
Character array[10]; // This is an array of Characters
array[0].setName("Bob"); // This sets the 0th Character's name to Bob
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.