实验一:(转自学堂在线《面向对象程序设计(C++)》课程视频)
#include <iostream>
using namespace std;
/*
void print(char* msg = "hello"){ //在我的电脑上实测:未通过
cout << msg << '#' << endl;
}*/
void print(char msg = 'A'){
cout << msg << '#' << endl;
}
int main(){
print('B');
print();
return 0;
}
实验二:(string字符串类型的声明与使用实验)
#include <iostream>
#include <string>
//注意:<string>是字符串类型声明的地方,而<cstring>是字符串函数声明的地方!
using namespace std;
/*
void print(string msg = "hello"){
cout << msg << '#' << endl;
}
*/
void print(char* msg = "hello"){
cout << msg << '#' << endl;
}
int main(){
print("beijing...");
print();
return 0;
}
当print()函数形参直接用char*时,编译器报错如下:
把print()形参改为const char*时,编译通过,结果正确:(实验发现:不加#include <string> 也行,只加const 在 char* 前面就可以了)
#include <iostream>
#include <string>
//注意:<string>是字符串类型声明的地方,而<cstring>是字符串函数声明的地方!
using namespace std;
/*
void print(string msg = "hello"){
cout << msg << '#' << endl;
}
*/
void print(const char* msg = "hello"){
cout << msg << '#' << endl;
}
int main(){
print("beijing...");
print();
return 0;
}
或者,直接用string类型定义形参。
#include <iostream>
#include <string>
//注意:<string>是字符串类型声明的地方,而<cstring>是字符串函数声明的地方!
using namespace std;
void print(string msg = "hello"){
cout << msg << '#' << endl;
}
int main(){
print("beijing...");
print();
return 0;
}
实验三:(缺省值的顺序实验)
以下代码将不能通过:
#include <iostream>
#include <string>
//注意:<string>是字符串类型声明的地方,而<cstring>是字符串函数声明的地方!
using namespace std;
void print(string name = "bill", int salary, string msg = "good"){
cout << name << ": " << salary << ", " << msg << endl;
}
int main(){
print("michael", 4500, "normal");
print( , 6000, );
return 0;
}
编译器报错信息:
修改为以下代码后,编译通过:
#include <iostream>
#include <string>
//注意:<string>是字符串类型声明的地方,而<cstring>是字符串函数声明的地方!
using namespace std;
void print(string name, int salary = 4500, string msg = "good"){
cout << name << ": " << salary << ", " << msg << endl;
}
int main(){
print("mickeal", 3000, "normal");
print("bill");
return 0;
}