image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
class B{
int x = 0;
public:
void setX(int px){x = px;}
void getX(){cout << x;}
};
class D:public B{
public:
using B::x;
void setX(int px){x = 2*px;}
};
int main(){
B * pb = new D;
pb->setX(15);
pb->getX();
return 0;
}
// 'x' is a private member of 'B' i 🎇🎇🎇
  • 使用名空间调用B.x,是不可见的,因为默认为private,所以没有using的权限,无法改变其使用权限
  • 如果删掉第11行代码也是错误的,因为此处的x依然是指B中的x,虽然内存中含有,但是不可见
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    //
    // Created by 13467 on 2022/11/15.
    //

    #include <iostream>

    using namespace std;

    class B {
    int x = 0;
    public:
    void setX(int px) {
    x = px;
    cout << "setX in B " << endl;
    }

    void getX() { cout << x << endl; }
    };

    class D : public B {
    public:
    // using B::x;
    int x{};

    void setX(int px) {
    x = 2 * px;
    cout << "setX in D"<< endl;
    }
    void getX(){
    cout << x << endl;
    }
    void methodInD(){
    cout << "methodInD" << endl;
    };
    };

    int main() {
    B *pb = new D;
    pb->setX(15); //set X in B
    pb->getX(); // 15
    // 因为没有加virtual,同时由于编译的缘故,所以pb只能通过声明的类型去使用方法,因此pb只能
    // 看到基类自己的方法,而无法看到派生类的方法
    pb->methodInD(); // 会报错: No member named 'methodInD' in 'B' i 🔥🔥
    D *pd = new D;
    pd->setX(10); // set X in D
    pd->getX(); // 20
    return 0;
    }
    隐藏函数?
    image.png
    编译正确,输出为0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    //
    // Created by 13467 on 2022/11/15.
    //

    #include <iostream>

    using namespace std;

    class B {
    int x = 0;
    public:
    void setX(int px) {
    x = px;
    cout << "setX in B " << endl;
    }

    void getX() { cout << x << endl; }
    };

    class D : public B {
    public:
    // using B::x;
    int x = 0;

    void setX() {
    x = 5;
    cout << "setX in D" << endl;
    }
    void setX(int px) { B::setX(2 * px); }
    };

    int main() {
    B *pb = new D;
    pb->setX(15); // setX in B 因为pb的类型是B类型,所以调用的B中的setX函数
    // pb->getX();
    D *pd = new D;
    pd->setX(5); // setX in B 因为pd中的setX内部调用了B空间下的setX,所以改变的是B空间中的x
    pd->getX(); // 10
    pd->setX(); // setX in D
    pd->getX(); // 10 调用的依然是B空间中的getX方法
    return 0;
    }