zoukankan      html  css  js  c++  java
  • 模板类继承-成员变量不可访问的问题

    在编写代码的时候,发现一个现象:

    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.
    ";
    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.
    ";
    32   return 0;
    33 }
    View Code

    运行结果:

  • 相关阅读:
    疑难杂症--数据库触发器导致批处理中变量无效
    Transaction And Lock--锁相关基础
    INDEX--关于索引的琐碎
    INDEX--索引相关信息查看
    INDEX--索引页上存放那些数据
    Transaction And Lock--解决死锁/锁的几种有效方式
    Transaction And Lock--由Lookup导致的死锁情况
    Transaction And Lock--由外键导致的死锁
    oozie中时间EL表达式
    SpringBoot-hello world
  • 原文地址:https://www.cnblogs.com/guoliushui/p/12777707.html
Copyright © 2011-2022 走看看