uacs2024

导航

复试C++14真题 看程序写结果5 虚函数、继承 易错?

复试C++14真题  看程序写结果5   虚函数、继承

#include <iostream>
using namespace std;
class A{
public:
    virtual void print()  {cout<<"A::print"<<endl;}
    //void print()  {cout<<"A::print"<<endl;}
};

class B: public A
{
public:
    void print()  {cout<<"B::print"<<endl;}
};

class C: public B{
public:
    void print()  {cout<<"C::print"<<endl;}
};

int main(){
    B b;
    C c;
    A* a;
    a = &b;
    a->print();  //B::print
    a = &c;
    a->print();  //C::print
}

如果是另一种

#include <iostream>
using namespace std;
class A{
public:
    //virtual void print()  {cout<<"A::print"<<endl;}
    void print()  {cout<<"A::print"<<endl;}
};

class B: public A
{
public:
    void print()  {cout<<"B::print"<<endl;}
};

class C: public B{
public:
    void print()  {cout<<"C::print"<<endl;}
};

int main(){
    B b;
    C c;
    A* a;
    a = &b;
    a->print();  //A::print
    a = &c;
    a->print();  //A::print
    return 0;
}

一定要注意父类与子类的同名函数是否为虚函数。因为没有注意到是虚函数,第一次做的时候就做错了。

posted on 2024-03-20 18:31  ᶜʸᵃⁿ  阅读(4)  评论(0编辑  收藏  举报