什么是匿名对象?
匿名对象到底是什么?
C++ 支持/有匿名对象吗?
What is an Anonymous Object exactly?
Does C++ support/have Anonymous Objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
匿名对象到底是什么?
C++ 支持/有匿名对象吗?
What is an Anonymous Object exactly?
Does C++ support/have Anonymous Objects?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(2)
C++ 标准没有定义术语“匿名对象”,但按理说,人们可以明智地使用该术语来描述任何没有名称的对象:
f(T());
void func(int, int, int);
我不会计算的是动态分配的对象:
从技术上讲,“对象”是任何区域存储 [1.8/1 in 2003],其中包括组成由
new int;
动态分配的整数的 X 字节。在
int* ptr = new int;
中,指针(它本身也是一个对象,不要忘记!)的名称为ptr
,而整数本身除了 <代码>*ptr。尽管如此,我还是犹豫是否称其为匿名对象。但同样,没有标准术语。
The C++ standard does not define the term "anonymous object", but it stands to reason that one might sanely use the term to describe any object that has no name:
f(T());
void func(int, int, int);
What I wouldn't count is dynamically-allocated objects:
Technically speaking, an "object" is any region of storage [1.8/1 in 2003], which would include the X bytes making up the integer dynamically-allocated by
new int;
.In
int* ptr = new int;
the pointer (itself an object too, don't forget!) has the nameptr
and the integer itself has no name other than*ptr
. Still, I'd hesitate to call this an anonymous object.Again, though, there's no standard terminology.
请注意,匿名对象和匿名类/类型是不同的概念。
这篇文章解释了后者。
这是一个简单的答案,但匿名对象基本上是编译器为其创建
类
的对象。例如,在 C# 中(我知道这有点无关紧要),您可以通过执行以下操作来创建匿名类型:
new { filename = value }
。编译器有效地创建了一个名为
AnonSomething1
[您不知道的随机名称] 的类,其中包含这些字段。因此,此时您刚刚创建了该AnonSomething1
的实例。 C++ 不允许内联匿名类类型(如 Java 和 C#,它们具有可以派生匿名类型的基 Object 类)。但是,您可以通过简单地编写
创建匿名结构并使用别名
myanonstruct
实例化它来创建匿名结构。此 C++ 代码没有定义类型,它只是创建一个具有 1 个实例的匿名类型。请参阅 C#:匿名类型
请参阅 Java:匿名类型
请参阅 C++ 结构:msdn
Note that anonymous object and anonymous class/type are different concepts.
This post explains the latter.
This is a simplistic answer, but an anonymous object is basically an object which the compiler creates a
class
for.For example in C# (I know this is kinda irrelevant) you can just create an anonymous type by doing:
new { filename = value }
.The compiler effectively creates a class called
AnonSomething1
[A random name you don't know] which has those fields. Therefore at that point you just created an instance of thatAnonSomething1
. C++ does not allow you to make anonymous class types inline (like Java and C# which have a base Object class which the anon types can derive).However you can make an anonymous struct by simply writing
which creates an anonymous struct and instantiates it with the alias
myanonstruct
. This C++ code does not define a type, it just creates an anonymous one with 1 instance.See C#: Anon Types
See Java: Anon Types
See C++ Structs: msdn