虚函数
我们可以把某个函数指定为final,如果我们已经把函数定义为final,则之后任何尝试覆盖该函数的操作都将引发错误。
1 struct B 2 { 3 virtual void f1(int) const; 4 virtual void f2(); 5 void f3(); 6 }; 7 8 struct D1: B 9 { 10 void f1(int) const override; 11 12 /* 13 void f2() override; //错误: B没有形如f2(int)的函数 14 void f3() pverride; //错误: f3不是虚函数 15 void f4() override; //错误: B没有形如f4的函数 16 */ 17 } 18 19 struct D2: B 20 { 21 void f1() const final; //不允许后续的其他类覆盖f1(int); 22 } 23 24 struct D3: D2 25 { 26 void f2(); 27 void f1(int) const; //错误:D2已经将f2声明成final 28 }
虚函数与默认实参
和其他函数一样,虚函数可以拥有默认实参,如果某次函数调用使用了默认实参,则该实参值由本次调用的静态类型决定。
1 #include <iostream> 2 using namespace std; 3 4 class A 5 { 6 public: 7 virtual void out(int i = 1) 8 { 9 cout << "class A " << i << endl; 10 } 11 }; 12 13 class B : public A 14 { 15 public: 16 virtual void out(int i = 2) 17 { 18 cout << "class B " << i << endl; 19 } 20 21 }; 22 23 int main() 24 { 25 A a; 26 B b; 27 A * p = &a; 28 29 p->out(); 30 p->out(3); 31 p = &b; 32 p->out(); 33 p->out(4); 34 35 return 0; 36 }
输出结果: