是否可以声明一个类而不实现它? (C++)

发布于 2024-07-20 04:24:00 字数 195 浏览 7 评论 0原文

我知道这些问题似乎含糊不清,但我想不出任何其他方式来表达它,但是,是否可以做这样的事情:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

月亮邮递员 2024-07-27 04:24:00

是的,这是可能的。 下面只是声明了 wsx

class wsx;

这种声明称为前向声明,因为当两个类相互引用时需要它:

class A;
class B { A * a; };

class A { B * b; };

那么需要其中一个类被前向声明。

Yes, that is possible. The following just declares wsx

class wsx;

That kind of declaration is called a forward declaration, because it's needed when two classes refer to each other:

class A;
class B { A * a; };

class A { B * b; };

One of them needs to be forward declared then.

玩世 2024-07-27 04:24:00

在您的示例中,

class wsx; // this is a class declaration

class wsx  // this is a class definition
{
public:
wsx();
}

是的,通过使用 class wsx; 可以声明一个类而不定义它。 类声明允许您声明该类的指针和引用,但不能声明该类的实例。 编译器需要类定义,以便知道为该类的实例分配多少内存。

In your example,

class wsx; // this is a class declaration

class wsx  // this is a class definition
{
public:
wsx();
}

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.

茶底世界 2024-07-27 04:24:00

这是类的定义

class wsx
{
public:
wsx();
}

这是构造函数的定义

wsx::wsx()
{
std::cout<<"WSX";
}

这是一个前向声明,表示该类将在某处定义

class wsx;

This is the definition of the class

class wsx
{
public:
wsx();
}

This is the definition of the constructor

wsx::wsx()
{
std::cout<<"WSX";
}

THis is a forward declaration that says the class WILL be defined somewhere

class wsx;
何以笙箫默 2024-07-27 04:24:00

是的。 但是不可能在不声明类的情况下定义它。

因为:每个定义也是一个声明。

Yes. But it is not possible to define a class without declaring it.

Because: Every definition is also a declaration.

把人绕傻吧 2024-07-27 04:24:00

你确实定义了类。 它没有数据成员,但这不是必需的。

You did define the class. It has no data members, but that's not necessary.

幻梦 2024-07-27 04:24:00

我不确定你是什么意思。 您粘贴的代码看起来是正确的。

I'm not sure what you mean. The code you pasted looks correct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文