10

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";
}

?

4

6 回答 6

22

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.

于 2009-05-16T01:55:20.773 回答
4

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.

于 2009-05-16T01:55:44.550 回答
4

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;
于 2009-05-16T01:56:17.637 回答
2

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

Because: Every definition is also a declaration.

于 2009-05-16T02:32:15.257 回答
0

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

于 2009-05-16T01:53:44.727 回答
-1

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

于 2009-05-16T01:52:51.297 回答