zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    深入浅出聊优化:从Draw Calls到GC
    关于Unity中植物树木烘焙后没有影子的解决方法
    Marvelous Designer 服装设计与模拟
    DAZ studio 4.9基础
    在下载SOPC代码的过程中遇到的一些错误
    开发工程师人生之路
    简易信号发生器的设计
    HDU A Simple Math Problem (矩阵快速幂)
    HDU Queuing (递推+矩阵快速幂)
    POJ 3233 Matrix Power Series(矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/jingyg/p/7443641.html
Copyright © 2011-2022 走看看