C++ forward declaration problem

2020-08-12 05:42发布

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.

7条回答
Emotional °昔
2楼-- · 2020-08-12 06:03

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

查看更多
小情绪 Triste *
3楼-- · 2020-08-12 06:06

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

查看更多
小情绪 Triste *
4楼-- · 2020-08-12 06:08

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;

};
查看更多
闹够了就滚
5楼-- · 2020-08-12 06:09

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;
}
查看更多
看我几分像从前
6楼-- · 2020-08-12 06:15

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.

查看更多
The star\"
7楼-- · 2020-08-12 06:19

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

查看更多
登录 后发表回答