C++ 虚函数 参数默认值

来源:互联网 发布:mac jenkins 开机启动 编辑:程序博客网 时间:2024/05/13 16:35

参考资料

  

  

  

此题目源自网易笔试。

  

#include <iostream>

using namespace std;

  

class Base{

public:

Base(){}

Base(bool arg){

foo(); // base42

}

virtual void foo(int i = 42) {

cout << "base" << i << endl;

}

};

  

class Derived: public Base{

public:

Derived(){}

Derived(bool arg):Base(arg){

foo(); // derive12

}

  

virtual void foo(int i = 12) {

cout << "derived" << i << endl;

}

};

  

void test1(){

Derived d;

Base &b1 = d;

Base b2 = d;

b1.foo(); // derived42

b2.foo(); // base42

}

  

void test2(){

Base *b = new Derived(true); // base42 derived12

delete b;

}

  

int main() {

test1();

test2();

}

  

  

test1结果:

derived42 

base42

原因:b1是d的引用,b1.foo()调用的是Derived的foo,因为b1类型是Base&,编译时决定了其foo的参数的默认值为Base的foo的参数默认值,所以b1.foo打印derived42;

Base b2 = d;调用Base的复制构造函数构造了出了b2,因此b2是Base对象,b2.foo()调用Base的foo方法,打印base42;

  

test2结果:

base42

derived12

new Derived(true)调用Derive(bool arg)构造函数,在执行前,调用Base(bool arg)方法,后者调用Base的foo方法,打印出base42;回到Derive(bool arg)的执行,调用Derived的foo方法,此时参数默认值为12,foo打印出derived12;

  

  

0 0