有如下程序: #include using namespace std; class vehicle{ public: virtual int wheels()eonst{return 0;} };

admin2017-02-18  39

问题 有如下程序:
    #include
    using namespace std;
    class vehicle{
    public:
    virtual int wheels()eonst{return 0;}
    };
    class Car:public Vehicle{
    public:
    int wheels()eonst{return 4;}
    };
    void f1(Vehicle v){cout<    void f2(Vehicle&v){cout<    void f3(Vehicle*pv){cout<wheels()<<’’;}
    int main(){
    Car c;
    f1(c);t2(c);t3(&c);
    return 0;
    }
    运行后的输出结果是(    )。

选项 A、4 4 4
B、0 4 4
C、4 0 4
D、4 4 0

答案B

解析 C++中,成员函数调用要触发多态需要满足两个条件:①被调用的成员函数必须是虚成员函数。②必须通过基类类型的引用或指针进行函数调用。
  题意中,main()函数首先构造Car对象c,然后将对象c传给三个函数f1()、f2()和f3(),其中f1()的参数是基类类型对象,函数体中调用的是基类的成员函数,输出0;12()的参数是基类类型对象的引用,函数体中调用的类成员函数是虚函数,满足多态条件,输出4;f3()的参数是基类类型对象的指针,甬数体中调用的类成员函数是虚函数,满足多态条件,输出4。故本题答案为B选项。
转载请注明原文地址:https://jikaoti.com/ti/fkt0FFFM
0

最新回复(0)