简体   繁体   English

C++ 预期的嵌套名称说明符

[英]C++ expected nested-name-specifier

I am getting the error expected nested-name-specifier before 'ClassB' but I have no idea why.expected nested-name-specifier before 'ClassB'但我不知道为什么。 Here is class A:这是 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现在这里是 class B,它使用了 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> .您的B::method1声明中有很多语法错误,所以我猜您希望B::method1接受A<T>类型的参数。

In that case your classA.h :在这种情况下,您的classA.h

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

and classB.h :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.第一个文件中存在语法错误,在模板 arguments 之后没有关闭 angular 括号。 It should be template <typename T> in that line.它应该是该行中的template <typename T>

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)....想想编译器在这里必须做什么——它读取第一个 header 文件,然后尝试从第二个 header 文件中读取所有源代码(因为它包含在内),然后它尝试再次从第一个 Z0397439FB995EZ0603F 读取所有源代码文件(因为它包含在第二个文件中)....

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 .至少从我在示例代码中看到的内容来看,您可以通过从第一个文件中删除#include "classB.h"并简单地将前向声明添加到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 . linker 会将前向声明链接到正确的classB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM