C++模板类继承中的作用域问题
来源:优易学  2011-11-16 17:05:28   【优易学:中国教育考试门户网】   资料下载   IT书店

  下面一段代码,大家可以试试,这样的问题经常被人忽略,出错还很难查:

  代码: 全选

  /*

  * template_scope.cpp

  */

  #include <iostream>

  using namespace std;

  int x = 8;

  void print() {

  cout << "hello" << endl;

  }

  template<typename T>

  class B {

  public:

  B() :

  x(0) {

  }

  explicit B(const int& v) :

  x(v) {

  }

  void print() const {

  cout << "B::print()" << endl;

  }

  protected:

  int x;

  };

  template<typename T>

  class A: public B<T> {

  public:

  void test_scope() const {

  cout << "x = " << x << endl; // 引用全局的x,输出 x = 8

  // cout << "x = " << B<T>::x << endl; // 必须显式调用父类的x

  print(); // 调用全局的print(),输出 hello

  // B<T>::print(); // 必须显式调用父类的函数

  }

  };

  class C {

  public:

  C() :

  x(0) {

  }

  explicit C(const int& v) :

  x(v) {

  }

  void print() const {

  cout << "C::print()" << endl;

  }

  protected:

  int x;

  };

  class D: public C {

  public:

  void test_scope() const {

  cout << "x = " << x << endl; // 用父类的x,输出:  x = 0

  print(); // 调用父类的print(),输出: C::print()

  }

  };

  int main() {

  A<int> a;

  a.test_scope();

  D d;

  d.test_scope();

  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训