当前位置:编程学习 > C/C++ >>

当派生类和基类的虚构函数默认实参不同时的传递问题

 当派生类和基类的虚构函数默认实参不同时;

派生类的实参将接收基类传递过来的默认参数

示列如下:

 

 


[cpp] 
#include <iostream>  
#include <ostream>  
#include <string>  
using namespace std; 
class B{ 
    public: 
        virtual void fun(int num = 0) 
        { 
            cout << "B = " <<  num << endl; 
        } 
}; 
class D: public B{ 
    public: 
        virtual void fun(int num = 1) 
        { 
            cout << "D = " << num << endl; 
        } 
}; 
int main() 

    D d; 
    B *p = &d; 
    p -> fun(); 
    B &b = d; 
    b.fun(); 
    return 0; 

#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class B{
    public:
        virtual void fun(int num = 0)
        {
            cout << "B = " <<  num << endl;
        }
};
class D: public B{
    public:
        virtual void fun(int num = 1)
        {
            cout << "D = " << num << endl;
        }
};
int main()
{
    D d;
    B *p = &d;
    p -> fun();
    B &b = d;
    b.fun();
    return 0;
}


运行结果如下:

D = 0
D = 0


 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,