简体   繁体   中英

Do I have to typedef on every Header file?

Let's say I have an std::vector of std::string s.

// Foo.h
class Foo {
    std::vector< std::string > mVectorOfFiles;
}

Then I used typedef to make it a StringVector type.

// Foo.h
typedef std::vector< std::string > StringVector;

class Foo {
    StringVector mVectorOfFiles;
}

If I have another class which takes a StringVector object...

// Bar.h
class Bar {
    Bar( const StringVector & pVectorOfFiles ); // I assume this produces a compile error (?) since Bar has no idea what a StringVector is
}

... do I have to use typedef again in the header file for Bar ?

// Bar.h
typedef std::string< std::vector > StringVector;
class Bar {
    Bar( StringVector pListOfFiles );
}

Is it possible to place the typedef std::vector< std::string > StringVector in a single file and have every other class know of the type StringVector ?

All files that #include "Foo.h" you get the typedef . So no, you don't have to replicate it in every file (as long as it includes Foo.h . You can place the typedef in a dedicated file if that suits your needs. In your case, this would make sense and would be an improvement, because Bar.h should not rely on the fact that Foo.h has the typedef and the necessary includes.

I would keep it simple and limit it to one type though, to be included in all files that use the type:

// StringVector.h
#ifndef STRINGVECTOR_H_
#define STRINGVECTOR_H_

#include <vector>
#include <string>

typedef std::vector< std::string > StringVector;

#endif

当然不是,你不必在所有头文件中输入typedef,只需在其余源文件包含的任何头文件中执行。

Create a class instead.

class Files {
};

Then you can use a forward declaration wherever it's needed;

class Files;

You will encapsulate behaviour appropriate to 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