有如下C++代码:
struct A{ void foo(){printf("foo");} virtual void bar(){printf("bar");} A(){bar();} }; struct B:A{ void foo(){printf("b_foo");} void bar(){printf("b_bar");} };
那么
A *p = new B; p->foo(); p->bar();
输出为:
#include <bits/stdc++.h> using std::string; using std::vector; using std::pair; using i64 = long long; const int INF = 1e9; class father{ public: void stru(){std::cout << "father is constructing!\n";}; virtual void father_two() {std::cout << "this is ur 2nd father...\n";}; father() {stru();}; }; class son: public father{ public: void stru() {std::cout << "that is a son\n";}; void father_two() override {std::cout << "now it's son here!\n";}; son() {std::cout << "son is constructing...\n";}; }; class grand: public son{ public: void stru() {std::cout << "this is grand......\n";}; void father_two() override {std::cout << "now it's grand here!\n";}; grand() {std::cout << "grand is constructing///\n";}; }; int main() { father *p = new grand; p -> stru(); p -> father_two(); return 0; }
father is constructing! son is constructing... grand is constructing///
father is constructing!然后
now it's grand here!因此,最终输出
father is constructing! son is constructing... grand is constructing/// father is constructing! now it's grand here!
【解析】A * p = new B; // A 的指针指向 B 的对象。
当执行 new B 时,调用 B 的无参构造函数,由于 B 继承 A,所以先调用 A 的构造函数,在 A 的构造函数中调用了虚函数 bar(),这时调用的是 A 的 bar()。如果在构造函数或析构函数中调用虚函数,则运行的是为构造函数或析构函数本人类型定义的版本,因为在构造子类的时候,首先回去调用父类的默认构造函数,此时子类还是未初始化的,所以不可能调用子类函数;
p->foo(); 因为 foo() 不是虚函数,所以执行的是 A 的 foo();
【静态联编和动态联编知识点讲解】
更多C++基础专业知识讲解,点击链接即可查看
https://www.nowcoder.com/link/zxyl-cpp89