法拉克系统 钻孔 编程:C++模板类继承中诡异的作用域问题

来源:百度文库 编辑:中财网 时间:2024/04/30 00:39:56

C++模板类继承中诡异的作用域问题

tiger

下面一段代码,大家可以试试,这样的问题经常被人忽略,出错还很难查:
代码: 全选
/*
* template_scope.cpp
*
*  Created on: 2009-8-19 下午06:13:28
*      Author: kwarph
*         Web: http://www.xuanyuan-soft.cn
*        Mail: kwarph@gmail.com
*/

#include
using namespace std;

int x = 8;

void print() {
    cout << "hello" << endl;
}

template
class B {
public:
    B() :
        x(0) {
    }

    explicit B(const int& v) :
        x(v) {
    }

    void print() const {
        cout << "B::print()" << endl;
    }

protected:
    int x;
};

template
class A: public B {
public:
    void test_scope() const {
        cout << "x = " << x << endl; // 引用全局的x,输出 x = 8
        // cout << "x = " << B::x << endl; // 必须显式调用父类的x

        print(); // 调用全局的print(),输出 hello
        // B::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 a;
    a.test_scope();

    D d;
    d.test_scope();
}


但是非模板类继承就没有这些问题。