因此虚函数在构造函数中,已经失去了虚函数的动态绑定特性。解确定缺省参数的值是在编译的时候

来源:互联网 发布:java中接口 编辑:程序博客网 时间:2024/06/06 04:40

因此虚函数在构造函数中,已经失去了虚函数的动态绑定特性。

 

class A

{

public:

        A()

        {

                Print();

        }

        virtual void Print()

        {

                printf("A is constructed./n");

        }

};

 

class B: public A

{

public:

        B()

        {

                Print();

        }

 

        virtual void Print()

        {

                printf("B is constructed./n");

        }

};

 

int _tmain(int argc, _TCHAR* argv[])

{

        A* pA = new B();

        delete pA;

 

        return 0;

}

 以上代码输出:

A is constructed.
B is constructed.


运行如下的C++代码,输出是什么?

class A

{

public:

    virtual void Fun(int number = 10)

    {

        std::cout << "A::Fun with number " << number;

    }

};

 

class B: public A

{

public:

    virtual void Fun(int number = 20)

    {

        std::cout << "B::Fun with number " << number;

    }

};

 


int main()

{

    B b;

    A &a = b;

    a.Fun();

}


输出B::Fun with number 10。由于a是一个指向B实例的引用,因此在运行的时候会调用B::Fun。但缺省参数是在编译期决定的。在编译的时候,编译器只知道a是一个类型a的引用,具体指向什么类型在编译期是不能确定的,因此会按照A::Fun的声明把缺省参数number设为10