C++ 类指针访问

#include <iostream>
using std::cout;
using std::endl;
using std::string;

class Base {
public:
    Base() {
        cout << "Construct base!" << endl;
    }
    Base(string source) {
        cout << "Construct base! Source: " << source << endl;
    }
    Base(const Base & copy) {
        cout << "Copy construct base!" << endl;
    }
    void show_func() {cout << "base_func" << endl;};
};

class Deliver : public Base {
public:
    Deliver(string source): Base("class deriver") {
        cout << "Construct Deliver! Souce: " << source << endl;
    }
    Deliver(const Deliver & copy): Base() {
        cout << "Copy construct deliver!" << endl;
    }
    void show_func() {cout << "deliver_func" << endl;};
};
int main() {
    Deliver deriver("variable deliver");
    Deliver *dp = &deriver;
    cout << "\n\n\n";

    cout << "\n1.dp -> show_func(): " << endl;
    dp -> show_func();

    cout << "\n2.((Base*)(dp)) -> show_func(): " << endl;
    ((Base*)(dp)) -> show_func();

    cout << "\n3.(*dp).show_func(): " << endl;
    (*dp).show_func();

    cout << "\n4.(Base(*dp)).show_func(): " << endl;
    (Base(*dp)).show_func();

    cout << "\n5.(Deliver(*dp)).show_func(): " << endl;
    (Deliver(*dp)).show_func();
}

输出:

1.dp -> show_func():
deliver_func

2.((Base*)(dp)) -> show_func():
base_func

3.(*dp).show_func():
deliver_func

4.(Base(*dp)).show_func():
Copy construct base!
base_func

5.(Deliver(*dp)).show_func():
Construct base!
Copy construct deliver!
deliver_func

分析:

  1. 使用成员提取,调用Deliver的方法。
  2. 将指针做一次强制类型转换后调用方法,由于指针类型是Base*,所以调用的是Base中的方法。
  3. 先寻址,再将调用方法,与1.等价。
  4. 先寻址,再做强制转换到Base,这里尽管指针对应的实例是Deliver类型的,但是由于强制转换的结构是Base类型的,这里会调用Base的拷贝构造函数。
  5. 先寻找,再做强制转换的Deliver,这里尽管指针对应的实例也是Deliver类型的,但C++还是对调用Deliver的拷贝构造函数。
最后修改:2020 年 07 月 07 日
如果觉得我的文章对你有用,请随意赞赏