问题描述
当函数的向前声明在源文件(.cpp)中工作时,为什么同样不适用于类?
When forward declarations of functions work in a source file (.cpp), why would the same doesn't work for classes ?
感谢。
// main.cpp
void forwardDeclaredFunction() ; // This is correct
class One ; // Why this would be wrong
int One:: statVar = 10 ;
void
One :: anyAccess() {
std::cout << "\n statVar:\t " << statVar ;
std::cout << "\n classVar:\t" << classVar ;
}
class One {
public:
void anyAccess() ;
static int statVar ;
private:
int classVar ;
} ;
int main (int argc, char * const argv[]) {
One *obj = new One ;
return 0;
}
void forwardDeclaredFunction() {
}
推荐答案
转发声明也可以用于类:
Forward declaration can work for classes too:
class Foo;
class Bar {
public:
Foo *myFoo; // This has to be a pointer, thanks for catching this!
};
class Foo {
public:
int value;
};
上面的代码显示了Foo类的前向声明,使用Foo *类型的变量class(Bar),然后是Foo类的实际定义。 C ++不在乎如果你留下的东西未实现,只要你在使用它的代码之前实现它们。定义指向某个类型的对象的指针不是使用其代码。
The above code shows a forward declaration of the Foo class, using a variable of type Foo* in another class (Bar), then the actual definition of the Foo class. C++ doesn't care if you leave things unimplemented as long as you implement them before using its code. Defining pointers to objects of a certain type is not "using its code."
快速,脏的回复,但我希望它有帮助。
Quick, dirty reply but I hope it helps.
编辑:声明未实现的类的非指针变量不会编译为回复。这样做正是我所说的使用它的代码。在这种情况下,只要调用Bar构造函数,就会调用Foo构造函数,因为它具有类型为Foo的成员变量。由于编译器不知道你计划以后实现Foo,它会抛出一个错误。对不起,因为我的错误;)。
Declaring a non-pointer variable of a class thats unimplemented will NOT compile as the replies stated out. Doing so is exactly what I meant by "using its code." In this case, the Foo constructor would be called whenever the Bar constructor is called, given that it has a member variable of type Foo. Since the compiler doesn't know that you plan on implementing Foo later on, it will throw an error. Sorry for my mistake ;).
这篇关于类,函数的前向声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!