[英]Class in a struct
I have two questions. 我有两个问题。
I know it is possible to declare class objects in structs. 我知道可以在结构中声明类对象。 But is it ethical to do that from design point of view?
但是从设计的角度来看这样做是否合乎道德?
In my scenario I have a structure with a huge number of member elements and I want to include a class object too. 在我的场景中,我有一个包含大量成员元素的结构,我也想包含一个类对象。 Here I have another question.
在这里,我还有一个问题。 If I memset() the whole struct the class handle is also reset.
如果我memset()整个结构,类句柄也将重置。 So, I check the size of the rest of the struct without the class object and subtract it while I call memset(), to get rid of this problem.
因此,我检查了没有类对象的结构的其余部分的大小,并在调用memset()时将其减去,以解决此问题。 (Please note that I am using STL class 'queue' here. And I cannot use sizeof() operator on the object, since it is not overloaded.)
(请注意,我在这里使用STL类'queue'。并且我不能在对象上使用sizeof()运算符,因为它没有被重载。)
But is this totally an unacceptable way to do that? 但这是一种完全不能接受的方式吗? Can you suggest some solution to this problem?
您能为这个问题提出一些解决方案吗?
struct
= class
(except for default visibility). struct
= class
(默认可见性除外)。
If you have a “huge number of members” you are probably doing something wrong, change your design, otherwise it becomes intractable. 如果您有“大量成员”,则可能是您做错了什么,请更改设计,否则将变得很棘手。
It is absolutely fine to nest classes and / or structs, where it makes sense. 在有意义的地方嵌套类和/或结构是绝对好的。 For instance, it's common to define nested classes for implementation details (so a
linked_list
class could have a node
member class). 例如,为实现细节定义嵌套类是很常见的(因此,
linked_list
类可以具有node
成员类)。
There's no such thing as a “class object”, and it's not clear what you mean by that. 没有“类对象”之类的东西,也不清楚您的意思。
Don't use memset
– you probably don't need it, just use normal constructors and assignment. 不要使用
memset
您可能不需要它,只需使用普通的构造函数和赋值即可。
And I cannot use sizeof() operator on the object
而且我不能在对象上使用sizeof()运算符
Wrong, you can use it. 错误,您可以使用它。
The solution is to avoid memset with classes and structures, and use constructors. 解决方案是避免使用类和结构的memset,并使用构造函数。 In C++11 you can use initialization lists too under various conditions.
在C ++ 11中,您也可以在各种条件下使用初始化列表。
There is no much functional difference between classes and structs in c++. 在c ++中,类和结构之间没有太多功能上的区别。 Structs exisist in c++ only for backward compatibility with C. So it is ok to have a class objects in structs.
在C ++中存在结构仅是为了与C向后兼容。因此在结构中包含类对象是可以的。 However I generally prefer structs that have only member variables with getter and setter.
但是,我通常更喜欢仅具有getter和setter成员变量的结构。 I dont use any functions inside struct that manupulate the data.
我没有在struct中使用任何函数来处理数据。 If i need that then i will use class.
如果我需要那我将使用课堂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.