C++/CLI中函数的工作方式与ISO/ANSI C++完全相同,但由于在C++/CLI中用跟踪句柄和跟踪引用替代了本地指针和引用,因此也带来一些变化,主要包括
-
CLR程序中函数的形参与返回值可以是数值类型、跟踪句柄、跟踪引用和内部指针。
-
如果某个形参是CLR数组,程序不需要另外的参数指定其大小,因为数组大小在属性Length中。
-
在C++/CLI程序中,不能像C++一样进行地址的算术运算,而应使用数组索引。( 内部指针不是可以算术操作吗?)
-
可以方便的返回CLR堆上的句柄,因为CLR有垃圾回收机制自动清理无用的内存。
-
C++/CLI函数接收可变长度参数的机制与本地C++不同。
-
C++/CLI中main()函数访问命令行实参的机制与本地C++不同。
下面就最后2条进行说明。
一、接收可变长度参数的函数
C++/CLI允许将形参列表指定为数组,数组声明前面加省略号,从而实现实参的长度可变。
int sum(...array<int>^ args) { // Code for sum }
上面的sum()函数可以接收任意数量的整数作为实参,在函数内部,通过访问数组args的元素就可以实现对实参的处理,实参个数由args的属性Length得到。下面是一个完整的例子,描述了该机制的工作过程。
- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::开始==>> [Ex5_15.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Ex5_15.cpp : main project file. #include "stdafx.h" using namespace System; double sum(...array<double>^ args) { double sum = 0.0; for each(double arg in args) sum += arg; return sum; } int main(array<System::String ^> ^args) { Console::WriteLine( sum(2.0, 4.0, 6.0, 8.0, 10.0, 12.0) ); Console::WriteLine( sum(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9) ); return 0; }
- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::结束==>> [Ex5_15.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
输出为
42 49.5
二、main()的实参
从前面的例子可以看出,CLR程序中main()函数仅有一个形参,它为String^类型的数组,这就将处理命令行实参简化为访问该数组的元素。下面的例子展示了这个用法。
此外还应注意:与本地C++中main()不同,命令行参数中不包括程序名称本身。
- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::开始==>> [Ex5_16.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Ex5_16.cpp : main project file. #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { Console::WriteLine(L"There were {0} command line arguments.", args->Length); Console::WriteLine(L"Command line arguments received are:"); int i=1; for each(String^ str in args) Console::WriteLine(L"Argument {0}: {1}", i++, str); return 0; }
- - - - - - - - - - - - - - - - <<== 华丽的分割线 ::结束==>> [Ex5_16.cpp] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
输出为
D:\My Documents\My Projects\Ex5_16\Debug>ex5_16 tring multiple "arguments values " 4.5 0.0 There were 5 command line arguments. Command line arguments received are: Argument 1: tring Argument 2: multiple Argument 3: arguments values Argument 4: 4.5 Argument 5: 0.0