c++ 虚函数的调用
基本的虚函数使用如下
#include <iostream>
#include <cstdio>
class A {
public:
int f(int a, int b) {
int ans = calc(a, b);
return ans;
}
protected:
virtual int calc(int a, int b) {
return a + b;
}
};
class B : public A {
protected:
int calc(int a, int b) override {
return a * b;
}
};
int main() {
B b;
int ans = b.f(2, 3);
printf("%d", ans);
return 0;
}
在构造函数和析构函数中不可调用虚函数。
构造函数中
在 Base 构造函数中调用了虚函数 virtualFunction(),由于此时派生类 Derived 部分还未构造,所以调用的是 Base 类的 virtualFunction() 版本,而不是 Derived 类重写的版本。
在析构函数中
先析构子类,再析构父类,析构父类的时候子类不存在了,调的虚函数也就不能生效了。
例子:
#include <iostream>
#include <cstdio>
class A {
public:
A() { f(1, 2); }
~A() { f(2, 3); }
int f(int a, int b) {
int ans = calc(a, b);
printf("%d\n", ans);
return ans;
}
protected:
virtual int calc(int a, int b) {
return a + b;
}
};
class B : public A {
public:
B() { f(3, 4);}
~B() { f(4, 5); }
protected:
int calc(int a, int b) override {
return a * b;
}
};
int main() {
B b;
// int ans = b.f(2, 3);
// printf("%d", ans);
return 0;
}
结果:
PS D:\code\c\test_override> ./1.exe
3
12
20
5