如何使用另一个类的静态集初始化该集...?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,首先您需要将
A::set1
公开访问:您还可以从
B
的定义中删除a
,因为您不需要A
的实例,您只需要访问其静态公共成员之一。然后,您的
comparison
函数应按如下方式修改:请注意,
insert
采用单个值并将其插入到集合中。这不足以复制整个集合。幸运的是,您有一个可以使用的赋值运算符,如上所示。Well, first you'll need
A::set1
to be publicly accessible:You can also remove
a
from your definition ofB
, since you don't need an instance ofA
, you only need to access one of its static public members.Then your
comparison
function should be modified as follows: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.我不确定
void B::comparison()
是什么,因为您从未声明过它,但一般语法是:该语法的例外是 if
set2
正在被初始化(即在类构造函数中),在这种情况下它看起来像:I'm not sure what
void B::comparison()
is since you never declared it, but the general syntax would be: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 类中的集合(而不保留其以前的内容)。在这种情况下,您需要将其指定为
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;
静态数据成员由类的所有对象共享,因此它不是任何对象的一部分。在这种情况下,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 byA::set1
. As already said by others, you needA::set1
to be publicly accessible.And if you want to insert
A::set1
intoset2
, the code would look like:set2.insert(A::set1.begin(), A::set1.end())