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
分析:
- 使用成员提取,调用
Deliver
的方法。 - 将指针做一次强制类型转换后调用方法,由于指针类型是
Base*
,所以调用的是Base
中的方法。 - 先寻址,再将调用方法,与
1.
等价。 - 先寻址,再做强制转换到
Base
,这里尽管指针对应的实例是Deliver
类型的,但是由于强制转换的结构是Base
类型的,这里会调用Base
的拷贝构造函数。 - 先寻找,再做强制转换的
Deliver
,这里尽管指针对应的实例也是Deliver
类型的,但C++还是对调用Deliver
的拷贝构造函数。