简体   繁体   中英

C++ expected nested-name-specifier

I am getting the error expected nested-name-specifier before 'ClassB' but I have no idea why. Here is class A:

#include "ClassB.h"
template<typename T
class A
{
//implementation
friend class B;
};

Now here is class B, which makes use of class A

#include "ClassA.h"
class B
{
template<typename T>
void method1(typename ClassA<T>::struct varName) {}
}

However, this doesn't work due to the error specified above. It has something to do with templating but I do not know what.

There are lots of syntax errors in your declaration for B::method1 , so I'm going to guess that you want B::method1 to accept an argument of type A<T> .

In that case your classA.h :

template<typename T
class A
{
    //implementation
    friend class B;
};

and classB.h :

#include "ClassA.h"
class B
{
    template<typename T>
    void method1(A<T> varName) {}
}

There is a syntax error in the first file the angular brackets are not closed after template arguments. It should be template <typename T> in that line.

And beyond that, you cannot mutually include headerfiles like that. Think of what the compiler has to do here - it reads the first header file, then tries to read all the source code from the second header file (because its included) and then it tries to read all the source code again from the first header file (because its included in the second)....

At least from what I see in the example code, you can fix this simply by removing the #include "classB.h" from the first file and simply add a forward declaration to classB . So the files would look like:

class B; // Forward declaration.

template <typename T>
class A
{
friend B;
...
};
#include "ClassA.h"
class B
{
template<typename T>
void method1(A<T> varName) {}
}

The linker will link the forward declaration to the correct classB .

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