c – 班级,功能的前瞻性声明
发布时间:2020-12-16 05:35:18 所属栏目:百科 来源:网络整理
导读:当函数的前向声明在源文件(.cpp)中工作时,为什么同样的方法对于类不起作用? 谢谢. // main.cppvoid forwardDeclaredFunction() ; // This is correct class One ; // Why this would be wrong int One:: statVar = 10 ;voidOne :: anyAccess() { std::cout
当函数的前向声明在源文件(.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() { } 解决方法
前进声明也可以为课程工作:
class Foo; class Bar { public: Foo *myFoo; // This has to be a pointer,thanks for catching this! }; class Foo { public: int value; }; 上面的代码显示了Foo类的前向声明,在另一个类(Bar)中使用Foo *类型的变量,然后是Foo类的实际定义.只要您在使用代码之前实现它们,C不在乎您是否将未实现的内容保留下来.定义指向某一类型对象的指针不是“使用其代码”. 快,肮脏的回复,但我希望它有帮助. 编辑:声明未实现的类的非指针变量将不会按照声明的回复进行编译.这样做正是我使用“代码”的意思.在这种情况下,每当调用Bar构造函数时,都会调用Foo构造函数,因为它具有类型为Foo的成员变量.由于编译器不知道您计划稍后实现Foo,所以会抛出错误.对不起,我错了 ;). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |