开发者

how to initilize the set using static set of another class...?

class A{
static set<string> set1;
};

class B{
set<string> set2;
public:
A a;
}

in main.cpp
void B::comparision()
{
set2.insert(a.set1)开发者_如何学Go;   //i am getting error
};

how can i initilize set2 with the value of set1.


Well, first you'll need A::set1 to be publicly accessible:

class A {
    public:
        static set<string> set1;
}

You can also remove a from your definition of B, since you don't need an instance of A, you only need to access one of its static public members.

Then your comparison function should be modified as follows:

void B::comparison()
{
    set2 = A::set1;
}

Note that insert takes a single value and inserts it into the set. This will not suffice to copy an entire set. Fortunately, you have an assignment operator you can use as shown above.


I'm not sure what void B::comparison() is since you never declared it, but the general syntax would be:

set2 = A::set1;

The exception to that syntax would be if set2 were being initialized (i.e., in a class constructor), in which case it would look like:

B::B : set2(A::set1) { }


By initialize I assume you want to copy all elements of the static set to the set in class B (without preserving its previous contents). In such case, you need to assign it as set2 = A::set1;


The static data member is shared by all objects of the class, so it is not a part of any object. In this case, set1 is not a part of object a. So you cannot access it by a.set1. Instead you can access the static data member by A::set1. As already said by others, you need A::set1 to be publicly accessible.

And if you want to insert A::set1 into set2, the code would look like: set2.insert(A::set1.begin(), A::set1.end())

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜