C++ 什么是匿名对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5330287/
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
What is an Anonymous Object?
提问by Sadique
What is an Anonymous Object exactly?
什么是匿名对象?
Does C++ support/have Anonymous Objects?
C++ 是否支持/具有匿名对象?
回答by Lightness Races in Orbit
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:
C++ 标准没有定义术语“匿名对象”,但可以合理地使用该术语来描述任何没有名称的对象:
- Temporaries:
f(T());
- Unnamed function parameters:
void func(int, int, int);
- 临时工:
f(T());
- 未命名的函数参数:
void func(int, int, int);
What I wouldn'tcount 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;
.
从技术上讲,“对象”是存储的任何区域 [2003 年的 1.8/1],其中包括由new int;
.
In int* ptr = new int;
the pointer (itself an object too, don't forget!) has the name ptr
and the integer itself has no name other than *ptr
. Still, I'd hesitate to call this an anonymous object.
在int* ptr = new int;
指针中(它本身也是一个对象,不要忘记!)具有名称ptr
,而整数本身除了*ptr
. 尽管如此,我还是会犹豫将其称为匿名对象。
Again, though, there's no standard terminology.
不过,同样没有标准术语。
回答by Bob Fincheimer
This is a simplistic answer, but an anonymous object is basically an object which the compiler creates a class
for.
这是一个简单的答案,但匿名对象基本上是编译器class
为其创建的对象。
For example in C# (I know this is kinda irrelevant) you can just create an anonymous type by doing:
例如在 C# 中(我知道这有点无关紧要),您可以通过执行以下操作来创建匿名类型:
new { filename = value }
.
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 that AnonSomething1
. 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).
编译器有效地创建了一个名为AnonSomething1
[您不知道的随机名称] 的类,其中包含这些字段。因此,那时您刚刚创建了 that 的一个实例AnonSomething1
。C++ 不允许您内联匿名类类型(如 Java 和 C#,它们具有匿名类型可以派生的基本 Object 类)。
However you can make an anonymous struct by simply writing
但是,您可以通过简单地编写匿名结构
struct {
int field1;
std::string field2;
} myanonstruct;
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.
它创建一个匿名结构并使用别名实例化它myanonstruct
。这段 C++ 代码没有定义类型,它只是创建了一个具有 1 个实例的匿名类型。
See C#: Anon Types
请参阅 C#:匿名类型
See Java: Anon Types
请参阅 Java:匿名类型
See C++ Structs: msdn
请参阅 C++ 结构:msdn