0

I'm working on a project now and I am confused on how to approach this.

class Unit: public Entity { string Name; int HP; int MP; int Agi; int Spr; int Def; int Atk; int Lvl; int Exp; std::vector<int> states; string unitType; public: int GetHP() {return HP}; int GetMP() {return MP}; int GetAgi() {return Agi}; int GetSpr() {return Spr}; int GetDef() {return Def}; int GetAtk() {return Atk}; int GetLvl() {return Lvl}; int GetExp() {return Exp}; std::vector<int>& GetStates() {return &states}; string GetUnitType() {return unitType}; virtual void SetHP(int newValue); virtual void SetMP(int newValue); virtual void SetAgi(int newValue); virtual void SetSpr(int newValue); virtual void SetDef(int newValue); virtual void SetAtk(int newValue); virtual void SetLvl(int newValue); virtual void SetExp(int newValue); 

I need to return a reference to "std::vector states" so that I can iterate through it and look for values. I believe I should be using a Set because I only have one value and there cannot be repeats, but I'll save that for later. Is the "std::vector& GetStates() {return &states}" correct? Should it be changed to "std::vector& const GetStates() {return &states}" or am I completely off? I saw a post on here similar to this but it didn't specifically answer my question as they weren't using it in the same pretense as this.

2 Answers 2

1

If states is a std::vector<int>, then &states is a std::vector<int>*, not a std::vector<int>&.

The descision to return a reference or not is made by the return type as provided in the function signature, not by the return statement in the implementation. Just do return states.

Sign up to request clarification or add additional context in comments.

Comments

0

Is the "std::vector& GetStates() {return &states}" correct?

No, there are syntax errors.

std::vector<int>& GetStates(){ return states; } 

is correct.

Should it be changed to

That's up to you to decide. If you return non-const reference,, then whoever requested vector, will be able to change it. If you return const refernce, it makes sense to declare method as

const std::vector<int>& GetStates() const{ return states; } 

Second const indicates that when you call this function, object's internal state won't change.

1 Comment

That makes sense, as I don't want it to be changeable when I use GetState. Since this is the core of it, GetState is only going to be used to check for its existence, where SetState will have the ability only to send data to be changed by the class to encapsulate changes within the class. At least that's how I see it working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.