using 关键字的作用

我们都知道可以使用using关键字引入命名空间,例如:using namespace std;

using还有个作用是在子类中引入父类成员函数。

1) 当子类没有定义和父类同名的函数(virtual也一样)时,子类是可以直接调用父类的函数的:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 class CBase
 6 {
 7 public:
 8     void print() { cout << "Base::print()" << endl; }
 9 };
10 
11 class CChild : public CBase
12 {
13 public:
14 };
15 
16 int main()
17 {
18     CChild child;
19     child.print();
20     return 0;
21 }

输出

1 Base::print()

2) 当子类定义了和父类同名的函数时,子类是调用自己的函数,子类的函数隐藏了父类的函数:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 class CBase
 6 {
 7 public:
 8     void print() { cout << "Base::print()" << endl; }
 9 };
10 
11 class CChild : public CBase
12 {
13 public:
14     void print() { cout << "CChild::print()" << endl; }
15 };
16 
17 int main()
18 {
19     CChild child;
20     child.print();
21     return 0;
22 }

输出

1 CChild::print()

3) 即使函数签名(函数的名称及其参数类型组合)不一样,也会隐藏父类的函数:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 class CBase
 6 {
 7 public:
 8     void print() { cout << "Base::print()" << endl; }
 9 };
10 
11 class CChild : public CBase
12 {
13 public:
14     void print(int a) { cout << "CChild::print()" << endl; }
15 };
16 
17 int main()
18 {
19     CChild child;
20     child.print();
21     return 0;
22 }

输出

1 test.cpp: In function ?.nt main()?.
2 test.cpp:20:14: error: no matching function for call to ?.Child::print()?
3 test.cpp:20:14: note: candidate is:
4 test.cpp:14:7: note: void CChild::print(int)
5 test.cpp:14:7: note:   candidate expects 1 argument, 0 provided

4)如果需要对子类对象使用父类的函数,就需要在子类中使用using引入父类成员函数:

 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 
 5 class CBase
 6 {
 7 public:
 8     void print() { cout << "Base::print()" << endl; }
 9 };
10 
11 class CChild : public CBase
12 {
13 public:
14     using CBase::print;
15     void print(int a) { cout << "CChild::print()" << endl; }
16 };
17 
18 int main()
19 {
20     CChild child;
21     child.print();
22     return 0;
23 }

输出

1 Base::print()
原文地址:https://www.cnblogs.com/jingyg/p/7443641.html