| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1217 人关注过本帖
标题:C++模板类继承中诡异的作用域问题
取消只看楼主 加入收藏
xyath
Rank: 1
来 自:苏州昆山
等 级:新手上路
帖 子:4
专家分:0
注 册:2009-11-7
结帖率:0
收藏
已结贴  问题点数:20 回复次数:0 
C++模板类继承中诡异的作用域问题
C++模板类继承中诡异的作用域问题
帖子由 tiger » 2009-08-19 18:30
下面一段代码,大家可以试试,这样的问题经常被人忽略,出错还很难查:
代码: 全选
    /*
    * template_scope.cpp
    *
    *  Created on: 2009-8-19 下午06:13:28
    *      Author: kwarph
    *         Web: http://www.
    *        Mail: kwarph@
    */
    #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();
    }

但是非模板类继承就没有这些问题。
收到的鲜花
  • flyingcloude2009-11-08 14:58 送鲜花  20朵   附言:学习了
搜索更多相关主题的帖子: 继承 模板 
2009-11-07 14:45
快速回复:C++模板类继承中诡异的作用域问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012082 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved