重写(重定义)父类里多个重载中的一个时,父类的其他重载都会被隐藏

来源:互联网 发布:淘宝天猫店铺怎么开 编辑:程序博客网 时间:2024/04/30 07:16
#include<iostream>
using namespace std;

/*分析:
父类中有两个重载了的虚函数 、两个重载了的非虚函数
子类里各重写(重定义) 了一个虚函数和一个非虚函数(参数为char型的)
但在调用子类对象的这四个函数时,对其中未重写(重定义)的参数为int型的两个函数,
     会把int型参数强制转换为适合重写(重定义)了的函数的char型参数然后调用重写(
     重定义)了的函数
这也说明了编译器在确定函数调用时,如果找不到完全符合的函数原型,会找最符合的,
也即,会找通过强制类型转换后能符合的
*/ 
/*the output:
s.v('a'):
this is Son::v(char c) and i'm override
s.v(4):
this is Son::v(char c) and i'm override
s.uv(3):
this is Son::uv(char c) and i'm redefining.
is the uv(int n) also redefining???
s.uv('a'):
this is Son::uv(char c) and i'm redefining.
is the uv(int n) also redefining???
???????. . .
*/
/*源码 
struct Father{
     Father(){
     }
     void virtual v(int n){
          cout<<"this is Father::v(int n):"<<n<<endl;
     }
     void virtual v(char c){
          cout<<"this is Father::v(char c):"<<c<<endl;
     }
     void uv(int n){
          cout<<"this is Father::uv(int n):"<<n<<endl;     
     }
     void uv(char c){
          cout<<"this is Father::uv(char c)"<<c<<endl;
     }
};
struct Son: public Father{
     Son(){
     }
     void v(char c){
          cout<<"this is Son::v(char c) and i'm override"<<endl;
     }
     void uv(char c){
          cout<<"this is Son::uv(char c) and i'm redefining.\nis the uv(int n) also redefining???"<<endl;
     }
};
int main(){
     Father f;
     Son s;
     cout<<"s.v('a'):"<<endl;
     s.v('a');
     cout<<"s.v(4):"<<endl;
     s.v(4);
     cout<<"s.uv(3):"<<endl;
     s.uv(3);
     cout<<"s.uv('a'):"<<endl;
     s.uv('a');
     return 0;     
}
*/


/*
这一例中把参数为char类型的两个函数(一个virtual一个不是virtual的)换成了没有参数的 
*/
/*分析: 
调用子类中没有重定义(重写)的int参数的函数时,会认为子类中没有定义这样的函数而报错。
     也就是说,父类中的重载,在子类中同名函数被重写(重定义) 时,都被隐藏了 
*/ 
/*疑问: 
编译器这样做是为什么呢 
是因为函数的函数名决定了其所有重载,所以在子类中重写(重定义)了所有重载中的一个
     后,无法实现不隐藏父类中其他同名的重载函数吗? 
还是标准认为重定义(重写)了一个 就应该重定义(重写)其所有的重载呢? 
*/ 
/*编译器报错:
error: no matching function for call to `Son::v(int)'
note: candidates are: virtual void Son::v()
error: no matching function for call to `Son::uv()'
note: candidates are: void Son::uv(int) 
*/
/*源码 
struct Father{
     Father(){
     }
     void virtual v(int n){
          cout<<"this is Father::v(int n):"<<n<<endl;
     }
     void virtual v(){
          cout<<"this is Father::v():"<<endl;
     }
     void uv(int n){
          cout<<"this is Father::uv(int n):"<<n<<endl;     
     }
     void uv(){
          cout<<"this is Father::uv()"<<endl;
     }
};
struct Son: public Father{
     Son(){
     }
     void v(void){
          cout<<"this is Son::v() and i'm override"<<endl;
     }
     void uv(void){
          cout<<"this is Son::uv() and i'm redefining.\nis the uv(int) also redefining???"<<endl;
     }
};
int main(){
     Father f;
     Son s;
     cout<<"s.v():"<<endl;
     s.v();
     cout<<"s.v(4):"<<endl;
     s.v(4);
     cout<<"s.uv(3):"<<endl;
     s.uv(3);
     cout<<"s.uv():"<<endl;
     s.uv();
     return 0;
}
*/
原创粉丝点击