简体   繁体   中英

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.

Using forward declaration when possible (pointers to classes, for example) also reduces complexity in the dependency tree of classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM