当函数的前向声明在源文件(.cpp)中工作时,为什么同样的不适用于类?
谢谢.
// 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() {
}
Run Code Online (Sandbox Code Playgroud)
The*_*iac 12
前向声明也适用于类:
class Foo;
class Bar {
public:
Foo *myFoo; // This has to be a pointer, thanks for catching this!
};
class Foo {
public:
int value;
};
Run Code Online (Sandbox Code Playgroud)
上面的代码显示了Foo类的前向声明,在另一个类(Bar)中使用Foo*类型的变量,然后是Foo类的实际定义.只要在使用代码之前实现它们,C++就不关心是否保留未实现的内容.定义指向某种类型对象的指针不是"使用其代码".
快速,肮脏的回复,但我希望它有所帮助.
编辑:声明未实现的类的非指针变量将不会像回复中所述那样编译.这样做正是我所说的"使用它的代码".在这种情况下,只要调用了Bar构造函数,就会调用Foo构造函数,因为它有一个类型为Foo的成员变量.由于编译器不知道您计划稍后实现Foo,因此会抛出错误.对不起,我错了 ;).
| 归档时间: |
|
| 查看次数: |
28537 次 |
| 最近记录: |