如何使用另一个类的静态集初始化该集...?

发布于 2024-11-01 10:50:45 字数 254 浏览 4 评论 0原文

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

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

in main.cpp
void B::comparision()
{
set2.insert(a.set1);   //i am getting error
};

我如何使用set1的值初始化set2

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

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

in main.cpp
void B::comparision()
{
set2.insert(a.set1);   //i am getting error
};

how can i initilize set2 with the value of set1.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

沫雨熙 2024-11-08 10:50:45

好吧,首先您需要将 A::set1 公开访问:

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

您还可以从 B 的定义中删除 a,因为您不需要 A 的实例,您只需要访问其静态公共成员之一。

然后,您的 comparison 函数应按如下方式修改:

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

请注意,insert 采用单个值并将其插入到集合中。这不足以复制整个集合。幸运的是,您有一个可以使用的赋值运算符,如上所示。

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.

巷子口的你 2024-11-08 10:50:45

我不确定 void B::comparison() 是什么,因为您从未声明过它,但一般语法是:

set2 = A::set1;

该语法的例外是 if set2正在被初始化(即在类构造函数中),在这种情况下它看起来像:

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

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) { }
梦在夏天 2024-11-08 10:50:45

通过初始化,我假设您想要将静态集的所有元素复制到 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;

‘画卷フ 2024-11-08 10:50:45

静态数据成员由类的所有对象共享,因此它不是任何对象的一部分。在这种情况下,set1 不是对象a 的一部分。所以你不能通过a.set1访问它。相反,您可以通过 A::set1 访问静态数据成员。正如其他人已经说过的,您需要 A::set1 才能公开访问。

如果要将 A::set1 插入到 set2 中,代码将如下所示:
set2.insert(A::set1.begin(), A::set1.end())

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())

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文