如何为嵌套类编写范围解析操作符函数头

How to write the scope resolution operator function header for nested classes?

本文关键字:操作符 函数 范围 嵌套      更新时间:2023-10-16

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

我在完成任务时遇到了麻烦,因为我甚至不会写框架代码!

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

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();
        };
    };
}

这些函数是如何被称为?

当涉及到这个问题时,我可以遵循一个公式吗?或者它更灵活,根据你的需要而不同?

谢谢你的帮助!

我正在使用visual studio,如果这改变了什么…

给定:

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 }

要在您的实现(.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
}