簡體   English   中英

如何重載下標運算符以允許一組RPG字符?

[英]How to overload the subscript operator to allow an array of RPG characters?

試圖重載我的下標操作符,這樣我就可以為我的游戲制作一個字符數組。 無法搞清楚這個大創意。 我想只是傳遞一個整數(即索引)並讓它返回調用對象的名稱(即字符本身)

下標運算符

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

你這些東西很混亂! 如果重載Character::operator[] ,則意味着您希望能夠像處理數組一樣處理Character對象。 也就是說,你會這樣做:

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

但那不是你想要的。 相反,你只需要一個Character數組。 您根本不需要重載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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM