简体   繁体   English

C++:关键字类 A 有什么作用? B级; class C;等文件开头完成?

[英]C++: What does having keyword class A; class B; class C;, etc. at the beginning of a file accomplish?

I'm in a file that has:我在一个文件中:

class A; 
class B; 
class C; 

What is the meaning of this where one just states classes?只说明类是什么意思?

Suppose a class B contains a pointer to another class M as a member, but none of the members of class M are referenced in the definition of class C :假设一个类B包含一个指向另一个类M作为成员,但没有类的成员的M在类的定义中引用C

class C {
  ...
  M* pM ;
  ...
} ;

Then it is not necessary that the complete definition of class M be available to the compiler when class C is defined.那么,当定义类C时,编译器就不必提供类M的完整定义。 But the compiler does need to know that M is a type.但是编译器确实需要知道M是一种类型。 This is what such declarations achieve: to make the above code snippet valid, you can simply tell the compiler that M is a class , like so:这就是这样的声明所实现的:为了使上面的代码片段有效,您可以简单地告诉编译器M是一个class ,如下所示:

class M ;
class C {
  ...
  M* pM ;
  ...
} ;

You can often avoid this by defining your classes in the right order.通常可以通过以正确的顺序定义类来避免这种情况。 But if two classes contain pointers to instances of each other, this is the only way to do it:但是如果两个类包含指向彼此实例的指针,这是唯一的方法:

class B ;
class A {
  ...
  B* pB ; // This would fail without the declaration of `class B`
  ...
} ;
class B {
  ...
  A* pA ;
  ...
} ;

It informs the compiler that these classes will be used inside your program.它通知编译器这些类将在您的程序中使用。 This is named class declaration.这就是命名类声明。 It is simmilar to declaring method and then defining it later.它类似于声明方法然后稍后定义它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM