【问题标题】:How to overload the subscript operator to allow an array of RPG characters?如何重载下标运算符以允许 RPG 字符数组?
【发布时间】:2013-04-27 20:35:20
【问题描述】:

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

下标运算符

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

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:

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

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

    但这不是你想要的。相反,您只需要Characters 的数组。你根本不需要重载operator[] 来做到这一点,你只需声明一个数组:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多