我可以在 C++ 中破坏结构吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3506456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:59:29  来源:igfitidea点击:

Can I destruct a structure in C++?

c++destructor

提问by Ramilol

Is there a way to destruct a structure (nota class)?

有没有办法破坏一个结构(不是一个类)?

回答by Pablo Santa Cruz

In C++a structis exactly the same as a classwith the exception of the default visibility on members and bases. So if there is a way to "destruct" a class, you can use the exact same way to "destruct" a structure.

C++ 中struct,aclass与a完全相同,除了成员和基的默认可见性。因此,如果有一种方法可以“破坏”一个类,那么您可以使用完全相同的方法来“破坏”一个结构。

So, if you have a struct s { }in your C++ program you can do this:

所以,如果你struct s { }的 C++ 程序中有一个,你可以这样做:

s *v = new s();
delete v; // will call structure's destructor.

回答by Arun

Except for the default access specifier ("private" for class, "public" for struct), everything else is same in C++ class and struct. So, YES, you can write and use destructors in struct in the same way that is done in class.

除了默认的访问说明符(“private”代表类,“public”代表结构),C++ 类和结构中的其他一切都是一样的。所以,是的,您可以像在类中那样在 struct 中编写和使用析构函数。

回答by Mark Ingram

Structs are identical to classes except the default visibility and inheritance are public (rather than private).

除了默认可见性和继承是公共的(而不是私有的)之外,结构与类相同。

So you can create and destroy structs just like this (the same as a class, or built in type):

所以你可以像这样创建和销毁结构(与类相同,或内置类型):

// Create on the heap, need to manually delete.
MyStruct *const pStruct = new MyStruct();
delete pStruct;

// Created on the stack, automatically deleted for you.
MyStruct struct;

回答by Charlie

Structs and classes are the same thing, there is just a technical difference (the default field of access) which happens due to a conceptual difference between the two. However every struct like a class call its constructors when the objects have to be created, and its destructor when its visibility field ends.

结构和类是一回事,只是技术上的差异(访问的默认字段)是由于两者之间的概念差异而发生的。然而,每个结构(如类)在必须创建对象时调用其构造函数,并在其可见性字段结束时调用其析构函数。

In C++ structs aren't less powerful than classes.

在 C++ 中,结构并不比类弱。