“没有命名类型”。但确实如此

时间:2017-12-14 08:26:25

标签: c++ file templates inheritance

我有

BaseAbstrac class => Baseabstrac.h文件

Derived1 class => Derived1.h和Derived1.cpp文件

Derived2 class => Derived2.h和Derived2.cpp文件

NestedClass class => NestedClass.h和NestedClass.cpp文件

以及main.cpp。

除了NestedClass.cpp之外,所有cpp文件都可以编译。

这是我的错误:

NestedClass.cpp:13:1: error: ‘NestedClass’ does not name a type
 NestedClass& Derived1<T>::NestedClass::operator++()

但它是名称类型,因为我将NestedClass.h包含在NestedClass.cpp

这是我的标题和实现文件:

BaseAbstract.h

#ifndef BASEABSTRAC_H
#define BASEABSTRAC_H
#include <iostream>

using namespace std;

    template <class T>
    class BaseAbstract{
    public:
        class NestedClass;
        virtual int count (const T& val)=0;
    };


    #endif

Derived1.h

#ifndef DERIVED_H
#define DERIVED_H

#include "BaseAbstrac.h"
#include <memory>

using namespace std;

template <class T>
class Derived1:public BaseAbstract<T>{

protected:
    shared_ptr<T>dataS;
    int sizeS;
    int capacity;

public:

    Derived1();

    class NestedClass;

    int count (const T& val);

};

#endif

Derived1.cpp

#include "Derived1.h"
using namespace std;

template<class T>
Derived1<T>::Derived1()
{
    sizeS = 0;
    capacity = 0;
}

NestedClass.h

#ifndef NESTEDCLASS_H
#define NESTEDCLASS_H

#include <memory>
#include <string>
#include "Derived1.h"
using namespace std;

template <class T>

class Derived1<T>::NestedClass
{
protected:
        T* data;
public:
    NestedClass();

    T* getData();
    NestedClass& operator++();
};

#endif

NestedClass.cpp

#include "NestedClass.h"


using namespace std;
template<class T>
Derived1<T>::NestedClass::NestedClass() { data = new T; }

template<class T>
T* Derived1<T>::NestedClass::getData() { return data; }

template<class T>
NestedClass& Derived1<T>::NestedClass::operator++()
{
    data++;
    return data;
}

Derived2.h

#ifndef DERIVED2_H
#define DERIVED2_H
#include "Derived1.h"

using namespace std;
template <class K,class V>
class Derived2:public Derived1<pair<K, V> >{
public:
    Derived2();


};

#endif

Derived2.cpp

 #include "Derived2.h"
    using namespace std;

template <class K,class V>
    Derived2<K,V>::Derived2():Derived1<pair<K, V> >()
    {

        this->capacity=10000;
    }

的main.cpp

#include <iostream>
#include <memory>
    using namespace std;

    int main(void){

        Derived1<int> a;

    }

1 个答案:

答案 0 :(得分:2)

的背景下
template<class T>
NestedClass& Derived1<T>::NestedClass::operator++()
{
    data++;
    return data;
}

没有定义全局NestedClass符号。您必须使用完整范围:

template<class T>
typename Derived1<T>::NestedClass& Derived1<T>::NestedClass::operator++()
{
    data++;
    return data;
}

您需要typename,因为NestedClass依赖名称as explained here

正如M.M在评论中所提到的,这也可以使用尾随返回类型来解决

template<class T>
auto Derived1<T>::NestedClass::operator++() -> NestedClass& 
{
    data++;
    return data;
}