当前位置:编程学习 > C/C++ >>

简单c++函数问题

在c++中,一个函数F()有返回值,在主函数中是否一定要用A(此返回值同类型变量)=F(),?
补充:我用bool和int类型的函数试过,答案是否定的,但对其他类型的是否也是这样

答案:嘿嘿,答完这个再睡 
---------------------------------------------------------------------
1.C++不同于C语言,C语言中用1和0表示是和否,C++中有专门的数据类型bool
2.也不一定非要这么写吧,想怎么写就怎么写了
3.括号类型的转换是C风格的,在C++中一般用static_cast进行类型转换,你可以看effective C++这本书,上面的某一章有专门介绍
---------------------------------------------------------------------

1: //-------------------------------------- 2: //说明:SOSO举例 3: //环境:VS2005 4: //作者: 5: //-------------------------------------- 6: #include "stdafx.h" 7: #include <iostream> 8: 9: using namespace std; 10: 11: //return int 12: int funInt() 13: { 14: return 9; 15: } 16: 17: //return bool 18: bool funBool() 19: { 20: return true; 21: } 22: 23: 24: //main 25: int main(int argc, char* argv[]) 26: { 27: cout << "----------------------------------------start-->" << endl; 28: cout << "you can write like this : (use a function) " << funInt() << endl; 29: 30: int iRes = funInt(); 31: cout << "you can write like this : (use a variable) " << iRes << endl; 32: cout << "------------------------------------------------" << endl; 33: 34: cout << "return bool but output int : " << funBool() << endl; 35: cout << "set output is a bool by using boolalpha : " << boolalpha << funBool() << endl; 36: 37: cout << "------------------------------------------------" << endl; 38: cout << "convert int to bool (C++ style) : " << static_cast<bool>(funInt()) << endl; 39: cout << "convert int to bool (C style) : " << (bool)(funInt()) << endl; 40: 41: cout << "------------------------------------------------" << endl; 42: cout << "convert bool to int (C++ style) : " << static_cast<int>(funBool()) << endl; 43: cout << "convert bool to int (C style) : " << (int)(funBool()) << endl; 44: 45: cout << "------------------------------------------------" << endl; 46: cout << "this is the end. Please bear with my faults... " << endl; 47: system("pause"); 48: return 0; 49: } 50: 51:

运行结果:


没有强制规定.其实是按你的需要而决定是否使用返回值的.

即直接让 f(); 做为1条语句也可以.

这样的话,函数执行完毕依然会有返回值,但返回值传递到主函数的时候,由于没有变量接收这个返回值,这个返回值就会被系统丢弃.

如果这个函数的返回值你根本不需要用到,可以直接 f();做为一条语句,无需定义多一个变量.

可以对该返回值进行强制转换、那样就可以不用同类型的变量接收了

回答完毕、

返回值和实参不一定要同类型的变量

不一这要用A=F()这样的形式呀.

除非这个返回值A在多处地方用到,为了方便就用A代替.

其他类型也一样的.

char F()

{

return 'a';

}

int main()

{

cout<<F()<<endl;//这里就直接用F()代替.

return 0;

}

上一个:用c++写strcat函数。
下一个:C++ 获取容器指示器

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,