簡體   English   中英

模板基類的訪問屬性,無需“使用”

[英]Access attribute of template base class without “using”

我想在模板派生類B的方法中使用模板基類A中定義的屬性。
到目前為止,我發現using作品。
但是,為A每個單個屬性編寫一個using語句很繁瑣。
如何避免編寫那么多的using語句?

#include <iostream>

using namespace std;

template <typename T>
class A{
    public:
        A(){
            a = 10;
        }
        //virtual destructor
        virtual ~A(){
            cout << "~A() is called" << endl;
        }
    protected:
        T a;
} ;

template <typename T>
class B : public A<T>{
    public:
        void f(void){
            cout << a << endl;
        }
        virtual ~B(){
            cout << "~B() is called" << endl;
        }
    private:
        using A<T>::a; //how to get rid of this?
} ;

int main(void){
    B<int> bb;
    bb.f();
}

因為要擴展一個類,它是依賴於模板參數, this成為一個從屬名稱。 您必須使用this明確:

template <typename T>
struct B : A<T>{
    void f(){
        std::cout << this->a << std::endl;
    }
};

或者甚至可以指定類名稱:

template <typename T>
struct B : A<T>{
    void f(){
        std::cout << A<T>::a << std::endl;
    }
};

第三種解決方案當然是using語句。

 // how to get rid of this? 

你可以寫

    void f(void){
        cout << A<T>::a << endl;
    }

要么

    void f(void){
        cout << this->a << endl;
    }

擺脫using語句。

暫無
暫無

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

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