简体   繁体   中英

Include in header files

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

gives compile time error. However, if I include <string> at top, it compiles correctly. I don't want to use include statements in headers,though. How can i do it?

Including headers in other headers is a completely necessary thing. It's wise to reduce it as much as possible, but fundamentally, if your class depends on std::string , then you have no choice but to #include <string> in the header. In addition, there's absolutely nothing wrong with depending on any and/or all Standard classes- they are, after all, mandated to be provided on any implementation. It's using namespace std; that's frowned upon.

You must include <string> in this case to be able to use std::string .

The only moment when you can avoid #including a header is when you're only using references or pointers of the object in your header. In this case you can use forward declaration. But since std::string is a typedef, you can't forward declare it , you have to include it.

I'm sure you're trying to follow the advice to try to #include as less as possible, but you can't follow it in this case.

std::string is defined in the <string> header file in the std namespace. You have to include it.

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

This is not exactly best practice. All header files should fulfill their own dependencies, so users of the header file do not need to care about dependencies. At least that is my humble opinion.

You may have heard that it's unwise to use using namespace std; in a header, which is true because anything including that header is stuck with all of that in the global namespace. Including the header file that you need is perfectly acceptable.

Unfortunately you can't get around it.

Even if your class definition looked like this:

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

then there's still not much you could do, as 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 headers is a definite no-no, you can usually get away with #include ing standard headers in your own headers, without worrying about it.

Possibly some crazy extern declaration would help, but that's not a way. Why don't you want to include in header files?

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