C++ Test answer.docx
- 文档编号:2690311
- 上传时间:2023-05-04
- 格式:DOCX
- 页数:14
- 大小:20.81KB
C++ Test answer.docx
《C++ Test answer.docx》由会员分享,可在线阅读,更多相关《C++ Test answer.docx(14页珍藏版)》请在冰点文库上搜索。
C++Testanswer
1.Describethedifferenceofthekeywordpublic,privateandprotected.
(描述关键字public,private和protected的区别。
)
Publicmembercanbeaccessedbyanyprogram.
Ifamemberisnotaccessiblefromtheotherpartoftheprogram,it’sprivate.
AprotectedmemberofaclassBasecanbeaccessedbyclassesderivedfromBase,butitisstillhiddenfromtherestoftheprogram.
公有的数据成员可以被任何程序访问
私有的数据成员不能被该程序以外的部分程序访问
受保护的基类的数据成员可以被基类继承自基类的派生类访问,但是类内可以访问,类外不可以访问
2.Pleasefindthebuginsidethefollowingcodeandmodifyit.
(请找到下面的代码里面的错误,并修改它。
)
#include
classA
{
public:
A(){}
~A(){}
};
classB:
publicA
{
public:
B()
{
_pVar=newint[100];;
}
~B()
{
delete[]_pVar;
}
private:
int*_pVar;
};
intmain()
{
A*pA=newB();//派生类的对象给基类对象赋值
deletepA;//基类指针对象被删除,则基类的析构函数必须是虚析构,否则结果未定义。
return0;
}
Note:
Basicclassdestructormustbevirtualifitmaybeinheriteted.//如果可以被继,基类的析构函数必须是虚析构。
考虑:
子类、父类构造&析构的调用顺序。
如果delete的是派生类的指针,调用的是派生类的析构函数,如果delete的是基类的指针,就会出问题,只有这时,没有将基类的析构函数声明为虚函数会出问题。
虽然类体系的析构函数的名字不一样,但是虚函数机制仍然起作用。
3.Whatproblemswillbegeneratedinthefollowingprogram?
Program1:
int*p=newint;
intvar=10;
p=&var;
Note:
ifusenewmustbedelete//即deletep;
Program2:
int*p=newint[20];
deletep;
//delete[]p;
4.Whatisthebenefitsoftheinlinefunction?
(内联函数的好处是什么?
)
Avoidfunctioncalloverhead(减少函数调用的开销)
5.Pleasedescribethedifferentfunctionalityof“Static”whenitisusedtodeclareavariableinthefunction,andwhenitisusedtodeclareaglobalvariable,andwhenitisusedtodeclareamembervariableintheclass.
(请描述“静态”时,当在函数中被用来声明一个变量,当它被用来声明一个全局变量,当它被用于声明类中的成员变量的不同功能。
)
StaticLocalVariables(静态局部变量)
1>Variablesdeclaredasstaticinafunctionarenotstoredwiththeotherlocalvariablesonstack.
在一个函数中变量被声明为静态时,不与其他局部变量在栈上存储
2>Theyactlikeglobalvariablesandretaintheirvaluebetweenfunctioncallsbutunlikeglobalvariablestheyareonlyvisiblefromwithinthefunction.i.e.theirscopeisonlythefunctionwheretheyaredeclared.
他们的行为像全局变量和函数调用之间保留其价值,但与全局变量不同,它们只在函数内可见。
即其范围是声明它们的功能。
3>Staticlocalvariablesareautomaticallyinitializedtozero.
静态局部变量自动初始化为零。
Staticglobalvariable(静态全局变量)
Itisusedinthefilethatdefinesthevariable.//它只在所在的原文件内使用有效
Staticmembersofaclass(一个类的静态成员)
Astaticmemberofaclassdoesnotbelongtoanyspecificobject.Itcanbeaccesseddirectlybyclass_name:
:
static_member.
一个类的静态成员不属于任何特定的对象,它可以直接通过类名:
:
静态成员/对象名.静态成员来被访问
Staticmemberfunction(静态成员函数)
1>Staticmemberfunctionarenotassociatedwithanyparticularobjectoftheirclass.,sotheydonothave‘this’pointer.
静态成员函数是不与任何特定的对象关联的,因此它不可以使用“This”指针。
2>Staticmemberfunctioncanaccessallstaticmembersoftheirclass,butnotthenon-staticmembersofobjectsoftheirclass.
静态成员函数可以访问所有的静态成员,但是不能访问非静态成员。
6.PleaseexplainthedifferenceofstructandclassintheC++language.
(请解释在C++语言中struct和class的区别)
Structdefaultispublic//C++中结构默认均为public
Classdefaultisprivate//C++中类的默认均为private
Inhanriteisthesame//继承是相同的
结构体继承
structC
{
intage;
doubleweight;
};
structD:
C
{
voidprint(){cout<<"ThisisD\n";}
};
7.Whatistheoverloadandwhatistheoverride?
Whenweoverloadtheoperator<<,wewriteitasthefollowing:
(什么是重载,什么是重写?
当我们重载运算符<<,我们编写如下:
)
ostream&operator<<(ostream&,foo&)//(fooisaclass)
Overload(重载)
Functionsmustbecalledbydifferentactualparameterlists.//函数调用的参数列表(个数、类型)不同
Thedifferencebetweentwofunctionisonlythereturnvaluetype,theycannotbeoverloaded.
//两个函数之间的区别仅仅是它们的返回值类型不同,他们就不能被重载
override(重写)
Thederivedclassdefineamemberfunctionwiththesameprototypeasamemberfunctioninthebaseclass.
//派生类定义一个成员函数作为成员函数在基类中相同的原型。
Thisderivedclassfunctionoverridesthebaseclassfunction.//这个派生类的函数覆盖基类的功能。
Overridingisaspecialcaseoffunctionoverloading.//重写是的函数重载的一种特殊情况。
Whydoesitreturnareferenceostream&insteadofostream?
(为什么返回一个引用的ostream)
TomakeFunctionchain//为了使用函数链
8.HowmanyconstructorsareprovidedindefaultintheC++classandpleaselistthem.
(C++的类中有多少构造函数被默认的提供了,并请列出他们。
)
Defaultconstructor//类中没有构造函数的声明,编译器将为未初始化的所有数据成员提供一个默认的构造函数
Defaultcopyconstructor//如果类中没有提供拷贝构造,编译器将会该类提供一个默认的拷贝构造函数
9.Pleasewritetheprototypeofthecopyconstructorandoverloadedassignment.Whenisthecopyconstructorinvoked?
(请写出拷贝构造函数和赋值重载的原型。
什么时候调用拷贝构造函数?
)
consta&operator=(consta&b)//5步
{
if(this!
=&b)//首先判断是否自身赋值,若不是
{
size=b.size;
delete[]rep;//现删除原来动态申请的空间
rep=newchar[size];//并申请一块新的空间
strcpy(rep,a.rep);//对新申请的空间赋值(对其他的数据成员赋值)
}
returnthis;//若是,返回*this
}
voida(consta&b)//2步
{
This->size=b.size;//等价与size=b.size;
rep=newchar[size];//开辟新空间,并用size对rep初始化,返回指针给rep
strcpy(rep,a.rep);//进行拷贝:
把对象a赋值到新的对象rep
}
1>anobjectisinitializedbyanexistingobject.//用一个现有的对象对一个新的对象初始化时
i.e.Ax;
A*p=newA(x);
2>anobjectispassedtoorreturnedfromafunctionbyvalue.//一个对象是通过函数传值的方式被传递或被返回时
10.Pleaseinterpretthefunctionalityofthree“const”inthefollowingmethoddeclaration:
(请解释在下面的方法声明中的三个单词“const”的功能)
constint*computeResult(constint&var)const;
<1><2><3>
1>Afunctionthatreturnsaconstantintpointer.//修饰一个函数返回一个常量int型的指针
pointertoconstants.Thevaluethatpointerpointtocan’tbemodified//指向常量的指针。
指针指向不能被修改的值
2>Afunctionthatacceptsaconstantpointerparameter//接受一个常量指针参数的函数
Theparametercan’tbemodifiedinthefunction.//函数的参数不能被修改
3>constantmemberfunction.Themembervariablescann’tbemodifiedbythefunction.//常量成员函数
Constfunctionmustbeamemberfunctionofaclass//类的成员函数才可以被constant修饰
Wemaypassanon-constantobjecttoaconstantfunction,butwecannotpassaconstantobjecttoanon-constantfunction.
Constantfunctioncaninvokeconstantfunctionandconstantvariablesonly.//类中的constant函数只能调用该类对象成员的constant函数,类中同一个函数可以有constant和非constant两个版本
11.Pleaseinterprethowmanyexceptionswillbethrewrespectivelyinthefollowingtwofunctions
.(在以下两个函数中有多少异常将被抛出)
voidf();
Ifnoexceptionspecifierisgiven,thefunctioncanthrowanyexception
没有throw(),表示可以抛出任何异常
voidf()throw()
Ifafunctionisnotexpectedtothrowanyexception,itcanbespecifiedbythrow()
不能抛出任何类型的异常
intfunc(intx)throw(int,Error_message)
thefunctionmaythroweitheranintoranobjectinclassError_messagge.
该函数可能抛出一个int或一个类Error_messagge的对象
//若抛出与声明的异常类型不同的异常,VC6.0中正常执行,Dev-cpp会出错。
12.Whatisthedifferencebetweenmapandmultimap?
Whatisthedifferencebetweenlistandvector?
关联容器:
map和multimap之间的区别是什么?
有序容器:
list和vector之间的区别是什么?
Map(映射)noduplicatedkeys//不允许有重复键
Multimap(多重映射)mayhaveduplicatekeys//可以有重复的键
Listdoubly-linkedlist;sequentialaccess;addordeleteanywhere//双向链表;顺序访问;添加或删除的任何地方
Segmentedbuffer,usedtostorelargedata.//分段缓冲区,用来存储大量的数据。
Operator[]isnotoverloaded.
Vectorrandomaccesstoanyelement;typicallyaddordeleteattheend//随机存取任何元素;通常在队尾添加或删除
Flatbuffer,usedtostoresmalldata.//平缓冲区,用来存储小数据。
Operator[]isoverloaded.
13.Pleasepointoutthebuginthefollowingcode.//请指出下面代码中的错误
#include
intmain()
{
inti=10;
cout<<”theresultis”<
return0;
}
Note:
nonamespace;//没有命名空间
usingnamespacestd;
14.Whatispolymorphism?
Howtoimplementpolymorphism?
Whatisabstractbaseclass?
Giveasampleofabstractbaseclass?
//什么是多态性?
如何实施多态性?
什么是抽象基类?
举一个抽象基类的样本
多态性:
是将子类类型的指针赋值给父类类型的指针,赋值之后,父对象就可以根据当前赋值给它的子对象的特性以不同的方式运作
多态性通过派生类重载基类中的虚函数型方法来实现.
abstractbaseclassiswhichincludepurevirtualfunction.
抽象基类是包括有纯虚函数(虚函数在定义时所赋的初值为0,可以没有函数体)的类
virtualtypeTfunction_name(parameter_list)=0;
15.Whatisthevirtualbaseclass?
Whatisthevirtualclassintroduced?
//什么是虚拟基类?
什么是虚拟类的?
ClassA:
publicvirualR//A类虚继承自R类,R类被称作“虚基类”,A类被称作“虚拟类”
16.PleaseusetheUMLdiagramtointerpretwhatis“IS-A”andwhatis“HAS-A”.
(请使用UML图来解释什么是“-A”,什么是“HAS-A”)
Is-aisinheritance//类之间的继承关系如果A是B,那么B就是A的基类
Has-aisCpmposition//对象和它的成员之间的从属关系如果A中有B,那么B就是A的组成部分
17.WhatistheSingletonpattern?
Whatisthebenefitofthispattern?
(Singleton模式是什么?
这种模式的好处是什么?
)
Ensureaclassonlyhasoneinstance,andprovideaglobalpointofaccesstoit.
//单例模式确保一个类只有一个实例,并提供一个访问它的全局访问点。
单例模式的优点:
1,实例控制:
单例模式防止其它对象对自己的实例化,确保所有的对象都访问一个实例。
2,伸缩性:
因为由类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性。
单例模式的好处就是:
类只实例化一次,省资源,节省开销,提高速度
18implementthefunctionstrcpy()
(实现拷贝函数)
Char*strcpy(char*strDest,constchar*strSrc)
{
If((strDest==NULL)||(strSrc==NULL))
Throw“Invalidargument(s)”;
Char*strDestCopy=strDest;
While((*strDest++=*strSrc++)!
=’\0’)
/*
while(*strSrc!
=‘\0’)
{
*strDest=*strSrc;
strDest++;
strSrc++;
}
*/
ReturnstrDestCopy;
}
19WriteaclassStringincludingdefaultconstruct,copyconstructor,overloadedassignmentoperator
(写一个String类的默认构造,拷贝构造函数,赋值运算符重载)
ClassString
{
Public:
String();
String(char*str);
String(constString&aString);
ConstString&operator=(constString&aString);
~String();
Private:
Char*_str;
}
String:
:
~String(void)//3分
{
delete[]m_data;
//由于m_data是内部数据类型,也可以写成deletem_data;
}
//String的普通构造函数
String:
:
String(constchar*str)//6分
{
if(str==NULL)
{
m_data=newchar[1];//若能加NULL判断则更好
*m_data=‘\0’;
}
else
{
intlength=strlen(str);
m_data=newchar[length+1];//若能加NULL判断则更好
strcpy(m_data,str);
}
}
//拷贝构造函数
String:
:
String(constString&other)//3分
{
intlength=strlen(other.m_data);
m_data=newchar[length+1];//若能加NULL判断则更好
strcpy(m_data,other.m_data);
}
//赋值函数
constString&String:
:
operate=(constString&other)/
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+ Test answer