简体   繁体   English

向量<Class>没有成员“功能”

[英]vector<Class> has no member "function"

I have two classes (Vector3 is an irrelevant class here):我有两个类(Vector3 在这里是一个无关的类):

class Room {
  public:
    Room();

  private:
    vector<Button> roombuttons[3];
};

and

class Button {
  public:
    Button();
    Button(Vector3 pos);

    void SetPos(Vector3 pos);

  private:
    Vector3 pos;
}

If I want to define Room() as:如果我想将Room()定义为:

Room::Room() { 
  roombuttons[0].SetPos(100,100,0);
}

I get an error saying class "std::vector<Button, std::allocator<Button>>" has no member "SetPos" Why am I not able to call the SetPos function of the Button class on Button instances in a vector?我收到一条错误消息,指出class "std::vector<Button, std::allocator<Button>>" has no member "SetPos"为什么我无法在向量中的 Button 实例上调用 Button 类的SetPos函数?

I want to have a Room instance with a couple Buttons that are stored in some kind of array so that I can use them like elements of an array.我想要一个 Room 实例,其中有几个按钮存储在某种数组中,以便我可以像使用数组元素一样使用它们。

The problem is that you are declaring roombuttons as an array of vector objects, thus roombuttons[0] is accessing the 1st vector , not the 1st Button .问题是您将roombuttons声明为vector对象数组,因此roombuttons[0]正在访问第一个vector ,而不是第一个Button So the error is correct, vector does not have a method named SetPos() .所以错误是正确的, vector没有名为SetPos()的方法。 You would need something more like this instead:你需要更像这样的东西:

roombuttons[0][0].SetPos(100,100,0);

But that is not what you are really asking for.但这不是你真正要求的。 You want an array of Button s, so either你想要一个Button数组,所以要么

  • change your array to be a single vector instead, and then populate it in the constructor:将数组改为单个vector ,然后在构造函数中填充它:

     class Room { public: Room(); private: vector<Button> roombuttons; }; Room::Room() : roombuttons(3) { roombuttons[0].SetPos(100,100,0); ... }
  • or, just get rid of the vector since you know up front how many Button s you want:或者,去掉vector因为你事先知道你想要多少Button

     class Room { public: Room(); private: Button roombuttons[3]; }; Room::Room() { roombuttons[0].SetPos(100,100,0); ... }

just do做就是了

vector<Button> roombuttons;

instead of代替

vector<Button> roombuttons[3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM