是否可以声明一个类而不实现它? (C++)
我知道这些问题似乎含糊不清,但我想不出任何其他方式来表达它,但是,是否可以做这样的事情:
#include<iostream>
class wsx;
class wsx
{
public:
wsx();
}
wsx::wsx()
{
std::cout<<"WSX";
}
?
I know the questions seems ambiguous, but I couldn't think of any other way to put it, but, Is it possible to do something like this:
#include<iostream>
class wsx;
class wsx
{
public:
wsx();
}
wsx::wsx()
{
std::cout<<"WSX";
}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,这是可能的。 下面只是声明了
wsx
这种声明称为前向声明,因为当两个类相互引用时需要它:
那么需要其中一个类被前向声明。
Yes, that is possible. The following just declares
wsx
That kind of declaration is called a forward declaration, because it's needed when two classes refer to each other:
One of them needs to be forward declared then.
在您的示例中,
是的,通过使用
class wsx;
可以声明一个类而不定义它。 类声明允许您声明该类的指针和引用,但不能声明该类的实例。 编译器需要类定义,以便知道为该类的实例分配多少内存。In your example,
So yes, by using
class wsx;
it is possible to declare a class without defining it. A class declaration lets you declare pointers and references to that class, but not instances of the class. The compiler needs the class definition so it knows how much memory to allocate for an instance of the class.这是类的定义
这是构造函数的定义
这是一个前向声明,表示该类将在某处定义
This is the definition of the class
This is the definition of the constructor
THis is a forward declaration that says the class WILL be defined somewhere
是的。 但是不可能在不声明类的情况下定义它。
因为:每个定义也是一个声明。
Yes. But it is not possible to define a class without declaring it.
Because: Every definition is also a declaration.
你确实定义了类。 它没有数据成员,但这不是必需的。
You did define the class. It has no data members, but that's not necessary.
我不确定你是什么意思。 您粘贴的代码看起来是正确的。
I'm not sure what you mean. The code you pasted looks correct.