当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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.

 myfunc ( vector<mystruct> &mystry );

So my question is I need to call this function with vector of structure. How can I declare this?

网友答案:

Use the scope operator :::

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.

网友答案:

When you declare the method of A, mystruct is already in scope, so you can use it without qualification:

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);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: