C++ forward declaration problem

2020-08-12 06:07发布

问题:

I have a header file that has some forward declarations but when I include the header file in the implementation file it gets included after the includes for the previous forward declarations and this results in an error like this.

error: using typedef-name ‘std::ifstream’ after ‘class’
/usr/include/c++/4.2.1/iosfwd:145: error: ‘std::ifstream’ has a previous declaration.

class ifstream;

class A
{
    ifstream *inStream;
}
// End of A.h

#include <ifstream>
using std::ifstream;

#include "A.h"

// etc

Whats the norm for working around this?

Thanks in advance.

回答1:

Don't forward declare std:ifstream - just import <iosfwd> instead.

ifstream is a typedef.

See here for further details: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.2/group__s27__2__iosfwd.html



回答2:

How did you forward declared it? The problem could be in that std::ifstream is a typedef and not a class.



回答3:

You actually have two problems.

The first is that forward declaring a typedef is rather difficult in C++, as Kirill has already pointed out.

Th second is that ifstream is a typedef for a specific template instantiation of basic_ifstream -- in order for the compiler to be able to expand the template, it must already have the body of the template defined, meaning you can't forward declare an instantiated template.



回答4:

If you want to forward declare some iostreams classes, you can simply include <iosfwd>. That header provides forward declarations for these classes.



回答5:

You're missing the semicolon after your class definition of A.



回答6:

check this

namespace std
{
    template<class E, class T> class basic_ifstream;
    template<class E> struct char_traits;
    typedef basic_ifstream<char, char_traits<char> > ifstream;
}


回答7:

Do the following (if you already include std header file before your own, there's no need to forward declare anymore):

In your cpp file:

#include <iostream>
#include "a.h"    

In your a.h file:

using namespace std;
class A {
  ifstream *instream;

};