简体   繁体   English

如何声明一个类的结构向量

[英]How to declare a vector of structure of a class

I have a class with a structure in it. 我有一堂课,里面有一个结构。 How do I create a vector of this structure type? 如何创建这种结构类型的向量?

Here is the example: 这是示例:

class A {
public:
    struct mystruct {   
        mystruct (int _label, double _dist) : label(_label), dist(_dist) {}   
        int label;
        double dist;
    };
}

Now in this class "A" there is a function as below. 现在在“ A”类中有一个如下功能。

   myfunc ( vector<mystruct> &mystry );

So my question is I need to call this function with vector of structure. 所以我的问题是我需要用结构矢量调用此函数。 How can I declare this? 我该如何声明?

使用范围运算符::

std::vector<A::mystruct>
class A 
{
public:
    struct mystruct
    {   
        mystruct ( int _label, double _dist ) : label (_label), dist (_dist) {}   
        int label;
        double dist;
    };

    void myfunc(std::vector<mystruct> &mystr);
}

As long as you declare myfunc after mystruct you should be fine. 只要在mystruct之后声明myfunc,就可以了。

When you declare the method of A, mystruct is already in scope, so you can use it without qualification: 声明 A的方法时, mystruct已经在范围内,因此可以不加限定地使用它:

class A {
public:
    struct mystruct {   
        mystruct (int _label, double _dist) : label(_label), dist(_dist) {}   
        int label;
        double dist;
    };

    void myfunc(std::vector<mystruct> &);
}

but when you call it, what you call the argument type depends on where you are: 但是调用它时, 调用的参数类型取决于您的位置:

void free_function() {
    A a;
    std::vector<A::mystruct> arg;
    a.myfunc(arg);
}

void A::another_method() {
    std::vector<mystruct> arg;
    this->myfunc(arg);
}

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

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