首页
外语
计算机
考研
公务员
职业资格
财经
工程
司法
医学
专升本
自考
实用职业技能
登录
计算机
有如下程序: #include<iostream> using namespace std; class Pet{ char name[10]; public: Pet(char*name){st
有如下程序: #include<iostream> using namespace std; class Pet{ char name[10]; public: Pet(char*name){st
admin
2009-08-25
12
问题
有如下程序:
#include<iostream>
using namespace std;
class Pet{
char name[10];
public:
Pet(char*name){strcpy(this->name,name);}
const char*getName()const {return name;}
virtual void call()const=0;
};
class Dog:public Pet{
public:
Dog(char*name):Pet(name){}
void call()const{cout<<"汪汪叫":}
};
class Cat:public Pet{
public:
Cat(char*name):Pet(name){}
void call()const{cout<<"喵喵叫";}
};
int main(){
Pet*pet1=new Dog("哈克"),*pet2=new Cat("吉米");
cout<<pet1->getName();pet1->call();cout<<end1;
cout<<pet2->getName();pet2->call();cout<<end1;
return 0;
}
程序的输出结果是______。
选项
答案
哈克汪汪叫 吉米喵喵叫
解析
此题考查的是虚函数与多态性。在成员函数的声明前面加上virual关键字,即可把函数声明为虚函数;在C++中,一个基类指针可以用于指向它的派生类对象,而且通过这样的指针调用虚函数时,被调用的是该指针实际所指向的对象类的那个重定义版本。即若基类和派生类中存在一模一样的成员函数,通过该基类指针调用这样的成员函数时,若这个成员函数被定义成虚函数,那么就调用派生类中的;否则就调用基类中的。本题中,在f()函数中,此题中,void call()在基类中被声明为虚函数,在主函数中,语句Pet*pet1=new Dog("哈克"),*pet2=new Cat("吉米");定义了基类的指针per1和pet2,并让它们分别指向派生类对象Dog和Cat。所以通过该指针调用call()时运行的是派生类的版本,分别输出哈克和吉米;而通过该指针调用 getName()运行的是基类的版本,分别输出汪汪叫和喵喵叫。
转载请注明原文地址:https://kaotiyun.com/show/0Ejp777K
本试题收录于:
二级C题库NCRE全国计算机二级分类
0
二级C
NCRE全国计算机二级
相关试题推荐
以下选项中,当x为大于1的奇数时,值为0的表达式是()。
有以下程序:#include#definef(x)2*x*xmain(){inta=2,s,t;s=f(a+1);t=f((a+1));printf(’’%d,%d\n’’,s,t);}程序运行后的输出结果是()。
下列给定程序中,函数fun的功能是:计算并输出下列级数的前N项和SN,直到SN+1的值大于q为止,q的值通过形参传入。例如,若q的值为50.0,则函数值应为49.394948。请改正程序中的错误,使它能得出正确的结果。注意:
以下选项中,合法的一组C语言数值常量是()。
有以下程序:#includevoidfun(int*p,int*q);main(){intm=1,n=2,*r=&m;fun(r,&n);printf(’’%d,%d’’,m,n);}voidfun(int*P,int*q){P
设x和y都是int类型,且x=1,y=2,则printf("%d%d",x,y,(x,y))的输出结果是()。
下面选项中关于“文件指针”概念的叙述正确的是
在关系数据库中,描述全局数据逻辑结构的是
C语言程序中,运算对象必须是整型数的运算符是
随机试题
属于医务人员之间关系的是()
中央乳糜管位于()。
禁止兴建向中华人民共和国海域及海岸()的中外合资经营企业、中外合作经营企业和外资企业。
水泥贮存期在()内,不一定要进行性能试验。
注册会计师甲、乙、丙共同出资设立一特殊的普通合伙制会计师事务所。因甲、乙在某次审计业务中故意出具不实审计报告,人民法院判决会计师事务所赔偿当事人50万元。根据合伙企业法律制度的规定,下列关于该赔偿责任承担的表述中,正确的是()。
2015年5月,张三因装修房屋向李四借款6万元。经友好协商,双方约定:张三应于2016年6月30日前归还本息共计6.1万元。但张三并未按期还款,李四多次索要无果,遂向人民法院提起诉讼,请求人民法院判决张三还款。下列说法正确的是()。
自身具有酪氨酸蛋白激酶活性的受体是
设函数f(x)在[0,+∞)上可导,f(0)=0,且其反函数为g(x).若g(t)dt=x2ex,求f(x).
"Flexibility"hasbecomeakeymetaphorpotentlyvivifyingavarietyofcontemporarylifediscourses.【F1】Ascapitalbecomesmore
DearMr.Black,Weareamid-sizedaccountingfirm.Ourstaffmembersarenothappywithourcurrentinsuranceplan,sowear
最新回复
(
0
)