开发者

C++ forward declaration problem

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 &l开发者_StackOverflow社区t;ifstream>
using std::ifstream;

#include "A.h"

// etc

Whats the norm for working around this?

Thanks in advance.


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


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


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.


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


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


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;
}


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;

};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜