Include in header files

class A{ private: std::string id; public: void f(); }; 

gives a compile-time error. However, if I include <string> on top, it compiles correctly. However, I do not want to use include statements in the headers. How can i do this?

+4
source share
7 answers

In this case, you must include <string> in order to be able to use std::string .

The only time you can avoid # including a header is when you use only links or pointers to an object in your header. In this case, you can use forward declaration. But since std :: string is a typedef, you cannot forward the declaration , you must include it.

I am sure that you are trying to follow the advice to try #include as little as possible, but you cannot follow it in this case.

+10
source

Including headings in other headings is absolutely essential. It is reasonable to reduce it as much as possible, but in principle, if your class depends on std::string , then you have no choice but to #include <string> in the header. In addition, there is absolutely nothing wrong with any and / or all standard classes - in the end, they should be provided for any implementation. This is using namespace std; frowning.

+12
source

std :: string is defined in the header file <string> in the std namespace. You must enable it.

+2
source

You can make sure that all the dependencies are fulfilled, including the necessary files in the implementation files, before including your other header files, i.e. make sure #include <string> appears on the first line of your implementation file (.cpp) before including your own header file.

This is not a good practice. All header files must fulfill their own dependencies, so header users do not need to worry about dependencies. At least that's my humble opinion.

+2
source

You may have heard that it is unreasonable to use using namespace std; in the title, which is true because something, including this title, is stuck with all of this in the global namespace. Including the header file you need is perfectly acceptable.

+1
source

Unfortunately, you cannot get around this.

Even if your class definition is as follows:

 class A { private: std::string* id; public: void f(); }; 

then there is still not much that can be done, since the forward declaring std::basic_string<char, etc> is a pain in the ass. I'm not even going to demonstrate.

Fortunately, although using namespace std in the headers is definitely no-no, you can usually get away with the standard #include headers in your own headers without worrying about it.

+1
source

Perhaps some crazy extern declaration will help, but it is not. Why don't you want to include in the header files?

-2
source

All Articles