C++ 正确返回向量引用

C++ 正确返回向量引用,c++,vector,reference,return,C++,Vector,Reference,Return,我现在正在做一个项目,我不知道该怎么做 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 H

我现在正在做一个项目,我不知道该怎么做

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);
类单位:公共实体{
字符串名;
int-HP;
int-MP;
int Agi;
int Spr;
int-Def;
int Atk;
国际级;
国际贸易;
向量状态;
字符串单位类型;
公众:
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&GetStates(){return&states};
字符串GetUnitType(){return unitType};
虚空SetHP(int newValue);
虚空SetMP(int newValue);
虚拟void SetAgi(int newValue);
虚空设置pr(int newValue);
虚拟void SetDef(int newValue);
虚拟void SetAtk(int newValue);
虚拟void SetLvl(int newValue);
虚拟void SetExp(int newValue);

我需要返回一个对“std::vector states”的引用,这样我就可以遍历它并查找值。我认为我应该使用一个集合,因为我只有一个值,不能重复,但我会保存它以备以后使用。“std::vector&GetStates(){return&states}”是否正确?是否应该将它更改为“std::vector&const GetStates(){return&states}“还是我完全错了?我在这里看到了一篇类似的帖子,但它没有具体回答我的问题,因为他们没有以与此相同的借口使用它。

如果
states
std::vector
,那么
states
std::vector*
,而不是
std::vector&

函数签名中提供的返回类型决定是否返回引用,而不是实现中的
return
语句。只需执行
returnstates

“std::vector&GetStates(){return&states}”是否正确

不,有语法错误

std::vector<int>& GetStates(){
    return states;
}
std::vector&GetStates(){
返回状态;
}
这是正确的

应该改成

这取决于您的决定。如果您返回non-const reference,,那么请求向量的人将能够更改它。如果您返回const reference,将方法声明为

const std::vector<int>& GetStates() const{
    return states;
}
常量std::vector&GetStates()常量{ 返回状态; }
Second const表示当调用此函数时,对象的内部状态不会改变。

这是有道理的,因为我不希望在使用GetState时它可以改变。因为这是它的核心,GetState只用于检查它的存在,其中SetState只能发送要由类更改的数据封装类内的更改。至少我认为它是这样工作的。