国庆Day3
一.选择题
1、适宜采用inline定义函数情况是( C)
A. 函数体含有循环语句
B. 函数体含有递归语句
C. 函数代码少、频繁调用
D. 函数代码多、不常调用substr
2、假定一个函数为A(int i=4, int j=0) {;}, 则执行“A (1);”语句后,i和j的值分别为(A )
A. 1和0
B. 1和4
C. 4和0
D. 4和1
3、下列有关重载函数的说法中正确的是(C )
A. 重载函数必须具有不同的返回值类型
B. 重载函数参数个数必须相同
C. 重载函数必须有不同的形参列表
D. 重载函数名可以不同
4、两个同名函数构成重载关系,以下那个选项不要求不同。( B)
A. 参数个数
B. 返回类型
C. 参数类型
D. 函数头后有无const
二.填空题
1、C++语言中如果调用函数时,需要改变实参或者返回多个值,应该采取___引用传递或指针传递____方式
2、执行下列代码
string str("HelloC++");
cout<<str.(5,3);
程序的输出结果是___C++____
3、下面是一个输入半径,输出其面积和周长的C++程序,在下划线处填上正确的语句。
#include <iostream>
#define pi 3.14
___using namespace std______;
int main()
{ double rad;
cout<<"rad=";
cin>>rad;
double l=2.0*pi*rad;
double s=pi*rad*rad;
cout<<"\n The long is:"<<l<<endl;
cout<<"The area is:"<<s<<endl;
}
4、程序实现大写字母转换成小写字母。
#include <iostream>
using namespace std;
char toLower(char c) {if (c >= 'A' && c <= 'Z') return c + 32;return c;
}
int main() {char c;cin >> c;cout << toLower(c) << endl;return 0;
}
5、执行下列代码
int i=230;
cout <<"i="<<hex <<i<<endl;
程序的输出结果为____i=e6_____。
三、编程题
3.1 有以下重载函数定义:
void f();
void f(int x);
void f(int m, int n);
void f(double d1, double d2=3.14);
则以下调用哪些是错误的,哪些可以并与那个函数匹配,编程验证
f(‘A’); //正确,匹配void f(int x);(但是‘A’会发生类型强转成int类型,即他的ASCII码值)
f( 5 ) ; //正确,匹配void f(int x);
f( 5.5 ); //正确,匹配void f(double d1, double d2=3.14);参数d2取3.14默认值
f(10, 20); //正确,匹配void f(int m, int n);
f(10, 23.4)://错误,类型不匹配
f(10.8, 24.87);//正确,匹配void f(double d1, double d2=3.14);
3.2 创建一个函数plus(),它把两个数值加在一起,返回它们的和,提供处理int、doble和string类型的重载版本,测试它们是否能处理下面的调用
#include <iostream>
#include <string>
using namespace std;// int
int plus(int a, int b)
{ return a + b; }// double
double plus(double a, double b)
{ return a + b; }// string
string plus(const string& a, const string& b)
{ return a + b; }int main() {cout << plus(1, 3) << endl; // 5cout << plus(1.2, 2.3) << endl; // 3.5cout << plus(string("Hello"), string("World")) << endl; // HelloWorldreturn 0;
}
思考:(1)给string版本的函数传送参数最有效的方式是什么?
string版本参数用const引用(const string&)最有效,避免字符串拷贝。
(2)double d = plus(3, 4.2)能否调用 ?
double d = plus(3, 4.2)可以调用,匹配double版本(int隐式转换为double)。