簡體   English   中英

模板繼承c ++

[英]template inheritance c++

我是c ++的新程序員。 我第一次使用模板。

我有一個抽象類和另一個擴展它的類。 但是抽象類的所有受保護成員都不被其他類識別:

class0.h:

template<class T>
class class0 {

protected:
    char p;
public:
    char getChar();
};

**class1.h**
template<class T>
class class1:public class0<T> {
public:
    void printChar();
};
template<class T>
void class1<T>::printChar(){
    cout<< p<<endl;//p was not declared in this scope
}

謝謝。 有一個偉大的一周=)

發生這種情況的原因是與模板的查找規則有關。

p不是依賴表達式,因為它只是一個標識符,而不是依賴於模板參數的東西。 這意味着將不會搜索依賴於模板參數的基類來解析名稱p 要解決此問題,您需要使用取決於模板參數的內容。 使用this->會這樣做。

例如

cout << this->p << endl;

要在依賴基類中查找名稱,需要滿足兩個條件

  • 這是必要的查找是不是不合格
  • 名稱必須依賴

C ++ 03中所述的這些規則與未經修改的C ++ 98規定的規則不同,后者滿足第二個項目符號(使名稱相關) 足以查找在從屬基類中聲明的名稱。

在實例化時查找依賴名稱,並且除非非限定查找之外的查找不會忽略依賴基類。 需要滿足這兩個條件才能找到在依賴基類中聲明的名稱, 單獨使用它們都不夠 要滿足這兩個條件,您可以使用各種結構

this->p
class1::p

兩個名稱p都是相關的,第一個版本使用類成員訪問查找 ,第二個版本使用限定名稱查找

我在VC9中沒有得到編譯器錯誤。 但是,代碼有幾個問題:首先,它不需要是一個模板類,因為它是當前編寫的...但是你可能只是為這個問題簡化了它? 其次,基類應該有一個虛擬析構函數。

#include <iostream>

using namespace std;

class class0 {
public:
   virtual ~class0(){}

protected:
    char p;
public:
    char getChar();
};

class class1 : public class0 {
public:
    void printChar();
};

void class1::printChar(){
    cout << p << endl;//p was not declared in this scope
}

int main() {
   class1 c;
   c.printChar();
   return 1;
}

由於您正在學習模板,我建議您在學習時不要混合概念(繼承和模板)。 從這樣一個簡單的例子開始......

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T add(const T& a, const T& b) {
   return a + b;
}

int main() {
   int x = 5;
   int y = 5;

   int z = add(x, y);
   cout << z << endl;

   string s1("Hello, ");
   string s2("World!");

   string s3 = add(s1, s2);
   cout << s3 << endl;

   return 1;
}

上面代碼中的重要概念是我們編寫了一個知道如何添加整數和字符串(以及其他許多類型)的函數。

很抱歉恢復這么老的問題,但我只是想添加一些我覺得有價值的東西,如果你的成員函數中有很多很多“p”。

class class1:public class0<T> {
public:
    using class0<T>::p; // add this line and in all member functions 
                        // will assume that "p" is the p from class0<T>
                        // very useful if you have hundreds of "p":s
                        // and don't want to replace every single one with "this->p"
    void printChar();
};

暫無
暫無

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

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