簡體   English   中英

如何為嵌套類編寫范圍解析運算符函數標頭?

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

嘿,我有一個相當簡單的問題,一些快速的Google搜索無法解決,所以我來這里尋求幫助。

我無法完成任務,因為我什至無法編寫框架代碼!

基本上我有一個像這樣的頭文件:

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

這些功能如何被稱為?

在解決這個問題時,我是否可以遵循一個公式?或者它更具靈活性,是否與您的需求有所不同?

謝謝您的幫助!

如果這有任何改變,我正在使用視覺工作室...

鑒於:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM