修改方法的特征
1.修改方法的返回值类型
如果原始方法的返回值类型是某个类的指针或引用,重写的方法可以将返回值改变为子类的指针或引用。这个叫协变返回。(我的理解是:子类“是一个“父类)
不能将返回值类型修改为完全不相干的类型。
2.如果在子类中使用父类虚方法的名称,但参数与父类中同名方法不同,那么这不是对父类方法的重写而是创建了一个新方法。原始的方法将被隐藏,子类无法调用。
可用using关键字显式地在子类中包含父类方法。
静态方法无法被继承。
当指定名称及一组参数重写某个方法时,编译器将隐式地隐藏父类中所有同名方法的其他实例。
C++中根据描述对象的表达式绑定默认参数,而不是根据实际对象类型绑定参数。
方法会继承而默认参数不会被“继承”:使用指向子类对象的父类指针调用的是子类重写的方法,而默认参数却是父类中的默认参数。
1 #include <iostream> 2 3 using namespace std; 4 5 6 class Super 7 { 8 public: 9 Super(){} 10 virtual void get(int i = 1){cout<<"There is Super. i="<<i;} 11 ~Super(){} 12 }; 13 14 class Sub :public Super 15 { 16 public: 17 Sub(){} 18 void get(int i = 2){cout<<"There is Sub. i="<<i;} 19 ~Sub(){} 20 }; 21 22 int main() 23 { 24 Super* ptr; 25 ptr = new Sub; 26 ptr->get(); 27 return 0; 28 }
运行结果: