[英]How can I avoid separating my class into headers and source files without compiler errors?
I'm a hobby programmer working on small projects. 我是从事小型项目的业余程序员。 I find that separating class definition from declaration only makes it harder to work with my classes.
我发现,将类定义与声明分开只能使处理类变得更加困难。 Compiler and linker errors related to multiple definitions or classes depending on each other's member functions are forcing me to do it though.
依赖于彼此的成员函数的与多个定义或类相关的编译器和链接器错误使我不得不这样做。 Is there any way to avoid the errors while not separating class definition from declaration?
有什么方法可以避免错误而不将类定义与声明分开? Failing that, is there a way to keep the class in one file?
失败了,有没有一种方法可以将类保存在一个文件中? I keep reading that I should never include a source file.
我一直在阅读,永远不要包含源文件。
Yes it is, but it may increase considerably your compilation times if you have complex classes. 是的,但是如果您使用复杂的类,则可能会大大增加编译时间。 It is as simple as to keep every thing "inside" the class:
就像将所有内容都保留在类中一样简单:
#ifndef __ACLASS_H__
#define __ACLASS_H__
class A {
public:
A() : i(0) {}
int getI() { return i; }
void setI(int _i) { i = _i; }
protected:
int i;
};
#endif
The #ifndef
directive is necessary to avoid multiple declarations. #ifndef
指令对于避免多个声明是必需的。
Using forward declaration when possible (pointers to classes, for example) also reduces complexity in the dependency tree of classes. 尽可能使用前向声明(例如,指向类的指针)还可以降低类的依赖关系树中的复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.