下面一段代碼,大家可以試試,這樣的問題經常被人忽略,出錯還很難查:
代碼: 全選
/*
* template_scope.cpp
*
* Created on: 2009-8-19 下午06:13:28
* Author: kwarph
* Web: http://www.xuanyuan-soft.cn
* Mail: [email protected]
*/
#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();
}