一、问答题
1.请说明类的纯虚函数、虚函数、静态成员函数、普通成员函数的区别。
2.什么情况下,类的析构函数应该声明为虚函数?为什么?
3.对于下面的代码:
class
myString;
myString
*
pStringArray
=
new
myString[
13
];
以下两种delete有什么区别?
deletepStringArray;
delete[]pStringArray;
二、说明题
下列题目,请写出输出结果,并要求说明原因。
4.下面的函数调用输出什么?
void
Test()
{
char
*
p
=
"
Test
"
;
cout
<<
&
p
<<
endl;
cout
<<
p
<<
endl;
cout
<<
*
p
<<
endl;
cout
<<
p[
0
]
<<
endl;
void
*
q
=
"
Test
"
;
cout
<<
&
q
<<
endl;
cout
<<
q
<<
endl
}
5.有如下的类:
class
CBase
{
public
:
virtual
void
Test()
const
{cout
<<
"
OutputfromCBase!
"
<<
endl;};
};
class
CDerived:
public
CBase
{
public
:
virtual
void
Test()
const
{cout
<<
"
OutputfromCDerived!
"
<<
endl;};
};
下面是两个函数:
void
Test1(CBasetest)
{
test.Test();
}
void
Test2(
const
CBase
&
test)
{
test.Test();
}
请问调如下的函数输出什么?
void
Test()
{
CDerivedoTest;
Test1(oTest);
Test2(oTest);
}
6.有如下的类:
class
B
{
public
:
B(){cout
<<
"
OutputfromtheconstructorofclassB!
"
<<
endl;}
~
B(){cout
<<
"
OutputfromthedestructorofclassB!
"
<<
endl;}
};
class
D1:
public
B
{
public
:
D1(
int
n){cout
<<
"
Theintegervalueis:
"
<<
n
<<
endl;};
~
D1(){cout
<<
"
OutputfromthedestructorofclassD1!
"
<<
endl;};
};
class
D2:
public
B
{
public
:
D2(
int
n){cout
<<
"
Theintegervalueis:
"
<<
n
<<
endl;};
~
D2(){cout
<<
"
OutputfromthedestructorofclassD2!
"
<<
endl;};
};
class
CTest
{
public
:
CTest():d2(
2
),d1(
1
){};
~
CTest(){};
private
:
D1d1;
D2d2;
};
请问调如下的函数输出什么?
7.有如下的类:
class
CBase
{
public
:
virtual
void
Test()
const
{cout
<<
"
OutputfromCBase!
"
<<
endl;};
};
class
CDerived:
public
CBase
{
public
:
void
Test()
const
{cout
<<
"
OutputfromCDerived!
"
<<
endl;};
};
请问调如下的函数输出什么?
void
Test()
{
CDerivedd;
CBase
*
pB
=
&
d;
pB
->
Test();
CDerived
*
pD
=
&
d;
pD
->
Test();
}
8.如果把上题中类CBase的Test方法改为非虚函数,输出又是什么?
9.有如下的类:
class
CBase
{
public
:
virtual
void
Test(
int
iTest
=
0
)
const
=
0
;
};
class
CDerived:
public
CBase
{
public
:
void
Test(
int
iTest
=
1
)
const
{cout
<<
iTest
<<
endl;};
};
请问调如下的函数输出什么?
void
Test()
{
CBase
*
p
=
new
CDerived;
p
->
Test();
deletep;
}
三、分析题
有如下的复数类:
class
complex
{
public
:
complex(
double
r
=
0.0
,
double
i
=
0.0
){re
=
r;im
=
i;};
double
real()
const
{
return
re;};
double
image()
const
{
return
im;};
private
:
double
re;
double
im;
};
complex
operator
+
(
const
complex
&
left,
const
complex
&
right)
{
return
complex(left.real()
+
right.real(),left.image()
+
right.image());
}
complex
operator
*
(
const
complex
&
left,
const
complex
&
right)
{
return
complex(left.real()
*
right.real()
-
left.real()
*
right.image(),left.real()
*
right.image()
+
left.image()
*
right.real());
}
请分析:
10.没有把运算符重载设置为类的成员函数有什么好处?
11.能不能把函数参数前面的const去掉?为什么?
12.类的成员函数real()和image()后面的const表示什么?这样写有什么好处?