简体   繁体   English

如何避免在没有编译器错误的情况下将类分为头文件和源文件?

[英]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.

相关问题 如何相应地构建代码(在头文件和源文件中),以免出现编译器和链接器错误? - How can I structure code accordingly (in headers and source files) so I don't get compiler and linker errors? 我如何在将我的类分成 ah 和 .cpp 文件时使用聚合? - how can i use aggregation while separating my classes into a .h and .cpp files? 如何避免包含类实现文件? - How can I avoid including class implementation files? 如何避免为不可变的类编写赋值运算符 - How Can I Avoid Writing an Assignment Operator for my Immutable Class 如何检查 C++ map 中的值而不会在“const”成员 function 中出现编译器错误? - How can I check values in a C++ map without getting compiler errors in a “const” member function? 如何与他人分享我的SFML游戏没有错误? - How can I share my SFML game with others without errors? 如何在标头中声明一个新类并在源文件中定义它而不会出现此错误? - How to declare a new class in the header and define it in the source file without this errors? 我怎样才能避免编译错误:std :: transform? - how can i avoid the compiler error: std::transform? 我如何在没有源文件的情况下使用静态库(在我的情况下为assimp) - How do I use a static library (in my case assimp) without the source files 如何在与主函数不同的源文件中定义类? - How can I define my class in a different source file to my main function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM