![]() |
The String Class and Functions |
The string is the most regular type of value used in an application. It can be a group of characters or symbol of any kind in any order. To represent it, as mentioned in Lesson 4, the string is represented in the C++/CLI language by the String class. As a managed type, a String object is declared as a handle. This is the same basis you use to involve a String object in a function. As a managed class, to return a String value from a function, when creating the function, specify that it returns a handle to String. Here is an example: String ^ GetPropertyAddress(); When implementing the function, in its body, do whatever you want but the rule, as always, is that you must return a string before the closing curly bracket. Here is an example: using namespace System;
String ^ GetPropertyAddress();
int main()
{
String ^ adrs = GetPropertyAddress();
Console::WriteLine(L"\nAddress: {0}", adrs);
return 0;
}
String ^ GetPropertyAddress()
{
String ^ strAddress;
Console::Write(L"Enter Property's Address: ");
strAddress = Console::ReadLine();
return strAddress;
}
Here is an example of running the program: Enter Property's Address: 6802 Lilas Drive Address: 6802 Lilas Drive Press any key to continue . . . A function that returns a string can take any type of argument such as a primitive type.
A String object can be passed to a function. As a managed type, the argument must be passed either as a tracking reference or as a handle. To pass the argument as a handle, follow the rules we reviewed, that is, precede the name of the argument with the ^ operator. Here is an example: using namespace System;
String ^ GetPropertyAddress();
void ShowAddress(String ^);
int main()
{
String ^ adrs = GetPropertyAddress();
ShowAddress(adrs);
return 0;
}
String ^ GetPropertyAddress()
{
String ^ strAddress;
Console::Write(L"Enter Property's Address: ");
strAddress = Console::ReadLine();
return strAddress;
}
void ShowAddress(String ^ strAdrs)
{
Console::WriteLine(L"\nAddress: {0}", strAdrs);
}
Here is an example of running the program: Enter Property's Address: 8804 Acacia Rd Address: 8804 Acacia Rd Press any key to continue . . . In the same way, you can pass as many strings as you judge necessary. Also, you can pass a mix of strings and other primitive types. |
|
|
||
| Previous | Copyright © 2006 FunctionX, Inc. | Next |
|
|
||