关于具有自引用的C ++类 [英] About C++ classes with self reference
问题描述
我有点困惑...
为什么C ++允许这样做:
static int t = 0;
class A
{
public:
A():m(t ++)
{
cout< ; C:< m < endl;
if(t> = 5)
{
A a; //<<<< -----这行
throw(a);
}
}
int m;
};
但这不是:
static int t = 0;
class A
{
public:
A():m(t ++)
{
cout < C:< m < endl;
}
A a; //<<<< -----这行
int m;
};
第二个没有按预期编译(是的,我知道为什么它不编译:在代码 A
仍然不完整)...
但是...第一个编译得很好做它应该做,即:崩溃应用程序在一个语句如: A a [10];
)。在构造函数中 A
是一个完整的类型吗?也可以给我一些C ++标准条目这种情况?
此情况的标准条目?
是的,草案C ++标准说一个类没有完全定义,直到关闭}
,这在 9.2
段 段:
类在classspecifier的closing}被认为是一个完全定义的对象类型(3.9)(或完整类型)。 [...]
并且类的所有非静态数据成员必须是完整的, em>:
非静态(9.4)数据成员不应具有不完全类型。特别地,类C不应包含类C的非静态成员,但它可以包含指向类C的对象的指针或引用。
但在构造函数中也在 2 内完成:
..]
虽然静态成员可以不完整, 9.4.2
段 b
$ b
静态数据成员在其类定义中的声明不是定义,并且可能是除了cv限定的void之外的不完整类型。 ]
不允许类包含自身也是有意义的,因为这将需要无限空间,因为自引用永远不会结束, I am a little bit confused ... Why is this allowed in C++: But this not: The second one is not compiling as expected (yes, I know why it's not compiling: at that point in code the But ... the first one compiles nicely (and does what it's supposed to do, ie: crashes the application on a statement like: Can also point me some C++ standard entries for this situation? Yes, the draft C++ standard says a class is not completely defined until the closing A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the classspecifier. [...] and all non-static data members of a class must be complete, from paragraph 9: Non-static (9.4) data members shall not have incomplete types. In particular, a class C shall not contain a non-static member of class C, but it can contain a pointer or reference to an object of class C. but it is considered complete within the constructor also within paragraph 2: [...]Within the class member-specification, the class is regarded as complete within function bodies, default arguments,[...] although static members can be incomplete, section The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void.[...] It also makes sense to not allow a class to contain itself since this would require infinite space since the self reference would never end, 这篇关于关于具有自引用的C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! A 包含
A
,其中包含 A
... static int t = 0;
class A
{
public:
A() : m(t++)
{
cout << "C:" << m << endl;
if(t >= 5)
{
A a; // <<<< ----- THIS line
throw( a);
}
}
int m;
};
static int t = 0;
class A
{
public:
A() : m(t++)
{
cout << "C:" << m << endl;
}
A a; // <<<< ----- THIS line
int m;
};
A
is still incomplete) ... A a[10];
). Is the A
a complete type in the constructor? Can also point me some C++ standard entries for this situation?
}
, this is in section 9.2
Class members paragraph 2:
9.4.2
Static data members paragraph 2:
A
contains A
which contains A
...