模板類繼承-成員變量不可訪問的問題


在編寫代碼的時候,發現一個現象:

  1. 模板類從一個父模板類繼承后,不能訪問其內部的protected成員變量,提示:not declare;
  2. 普通類從一個父模板類繼承后,可以訪問其內部的protected成員變量,可正常編譯和使用;

對於第1個現象,如果想正常使用需要加上父模板類的域名; 

下面上代碼

  1. 模板類繼承模板類
 1 #include <iostream>
 2 namespace test
 3 {
 4 template <typename T>
 5 class Base
 6 {
 7 public:
 8   void Show()
 9   {
10     std::cout << "hello world1! Base. a = " << a << std::endl;
11   }
12 
13 protected:
14   int a = 0;
15 };
16 
17 template <typename T>
18 class Child : public Base<T>
19 {
20 public:
21   void Show()
22   {
23     std::cout << "hello world1! Child. a = " << a << std::endl;
24   }
25 };
26 } // namespace test
27 
28 int main()
29 {
30   test::Child<int> ch;
31   ch.Show();
32   std::cout << "main.\n";
33   return 0;
34 }
View Code

 

運行結果:

 

 

 

 

對成員變量a增加基類域名后編譯通過:

 

 

 

  1. 普通類繼承模板類

 

 1 #include <iostream>
 2 namespace test
 3 {
 4 template <typename T>
 5 class Base
 6 {
 7 public:
 8   void Show()
 9   {
10     std::cout << "hello world1! Base. a = " << a << std::endl;
11   }
12 
13 protected:
14   int a = 0;
15 };
16 
17 class A : public Base<int>
18 {
19 public:
20   void Show()
21   {
22     std::cout << "hello world1! A. a = " << a << std::endl;
23   }
24 };
25 } // namespace test
26 
27 int main()
28 {
29   test::A ch;
30   ch.Show();
31   std::cout << "main.\n";
32   return 0;
33 }
View Code

 

 

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM