如何为嵌套类编写范围解析运算符函数头?

时间:2015-09-24 21:07:18

标签: c++ templates data-structures implementation scope-resolution

嘿,我有一个相当简单的问题,一些快速谷歌搜索无法解决,所以我来这里寻求帮助。

我在完成任务时遇到了麻烦,因为我甚至无法编写骨架代码!

基本上我有一个像这样的头文件:

namespace foo{
    class A {
    public:
        class B {
            B(); 
            int size();
            const int last();
        };
    };
}

我想知道如何在实现文件中引用文件外的这些人。

奖金:

namespace foo{

    template<typename T>
    typename
    class A {
    public:
        class B {
            B(); 
            int size();
            const int last();
        };
    };
}

这些功能如何被称为?

是否有一个我可以遵循的公式,或者它是否更灵活,根据您的需求而有所不同?

感谢您的帮助!

如果改变任何东西,我正在使用视觉工作室......

2 个答案:

答案 0 :(得分:4)

假设:

namespace foo{
    class A {
    public:
        class B {
            B(); 
            int size();
            const int last();
        };
    };
}

size或last函数定义的完整名称为:

int foo::A::B::size() {...}
const int foo::A::B::last() {...}

假设:

namespace foo{

    template<typename T>
    typename
    class A {
    public:
        class B {
            B(); 
            B & operator ++();
            int size();
            const int last();

            template< typename I, typename R>
            R getsomethingfrom( const I & );
        };
    };
}

函数定义为:

template <typename T> int foo::A<T>::B::size() { ... }
template <typename T> const int foo::A<T>::B::last() { ... }

对于这些,获取指向成员函数的指针将是:

auto p = &foo::A<T>::B::size;

构造函数定义为:

template<typename T> foo::A<T>::B::B() {}

制作以下内容之一:

foo::A<T>::B nb{}; // note, with nb() it complains

运算符函数定义在模板中返回对B的引用,很棘手:

template<typename T>         // standard opening template....
typename foo::A<T>::B &        // the return type...needs a typename 
foo::A<T>::B::operator++()     // the function declaration of operation ++
{ ... return *this; }        // must return *this or equivalent B&

如果您好奇,如果模板函数在B内,如getsomethingfrom,那么函数的定义是:

template< typename T>                       // class template
template< typename I, typename R>           // function template
R foo::A<T>::B::getsomethingfrom( const I & ) // returns an R, takes I
{ R r{}; return r }

答案 1 :(得分:0)

要在您的实现(.cpp)文件中使用该类,您可以使用:

namespace foo{
    A::B::B(){
        // this is your inner class's constructor implementation
    }

    int A::B::size(){
        // implementation for you size()
        int res = last(); // access the method last() of the same object
        return res;
    }

    const int A::B::last(){
        // implementation of last()
        return 42;
    }

}

void main(){
    foo::A a; // construct an object of A
    // can't do anything useful as the methods of A::B are all private
}