MOOC清华《面向对象程序设计》第2章:函数参数的缺省值实验

实验一:(转自学堂在线《面向对象程序设计(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;  
}  



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值