Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Руководство_по_C++_CLI.doc
Скачиваний:
4
Добавлен:
01.07.2025
Размер:
8 Мб
Скачать
☆

7.1.5A String as a Member Variable of a Class

A string is one of the most sought members of a class. It allows the member variable to carry any type of value, like any combination of characters or symbols included in double-quotes. As stated already, in C++/CLI, a string is mostly identified with the String class. Because the String class is a managed type, it must be declared on the managed heap as a handle. This is done using the ^ operator. Here are examples:

public value class CHouse

{

public:

String ^ PropertyNumber;

String ^ Address;

String ^ City;

String ^ State;

String ^ ZIPCode;

__wchar_t TypeOfHome;

int Bedrooms;

double Bathrooms;

Byte Stories;

int YearBuilt;

int Condition;

__wchar_t Style;

double Value;

};

To access a String member variable, use the -> operator and you don't have to allocate its memory. Here are example:

using namespace System;

public value class CHouse

{

public:

String ^ PropertyNumber;

String ^ Address;

String ^ City;

String ^ State;

String ^ ZIPCode;

__wchar_t TypeOfHome;

int Bedrooms;

double Bathrooms;

Byte Stories;

int YearBuilt;

int Condition;

__wchar_t Style;

double Value;

};

int main()

{

CHouse ^ home = gcnew CHouse;

home->PropertyNumber = "288635";

home->Address = "6808 Lilas Drive";

home->City = "Silver Spring";

home->State = "MD";

home->ZIPCode = "20904";

home->TypeOfHome = L'S';

home->Bedrooms = 5;

home->Bathrooms = 1;

home->Stories = 3;

home->YearBuilt = 1992;

home->Condition = 2; // Good, may need minor repair

home->Style = L'M'; // Highrise

home->Value = 555825;

Console::Write("Property #: ");

Console::WriteLine(home->PropertyNumber);

Console::Write("Address: ");

Console::WriteLine(home->Address);

Console::Write(" ");

Console::Write(home->City);

Console::Write(", ");

Console::Write(home->State);

Console::Write(" ");

Console::WriteLine(home->ZIPCode);

Console::Write("Type of Home: ");

Console::WriteLine(home->TypeOfHome);

Console::Write("Number of Bedrooms: ");

Console::WriteLine(home->Bedrooms);

Console::Write("Number of Bathrooms: ");

Console::WriteLine(home->Bathrooms);

Console::Write("Number of Stories: ");

Console::WriteLine(home->Stories);

Console::Write("Year Built: ");

Console::WriteLine(home->YearBuilt);

Console::Write("Condition: ");

Console::WriteLine(home->Condition);

Console::Write("Style: ");

Console::WriteLine(home->Style);

Console::Write("Property Value: ");

Console::WriteLine(home->Value);

Console::WriteLine();

return 0;

}

This would produce:

Property #: 288635

Address: 6808 Lilas Drive

Silver Spring, MD 20904

Type of Home: S

Number of Bedrooms: 5

Number of Bathrooms: 1

Number of Stories: 3

Year Built: 1992

Condition: 2

Style: M

Property Value: 555825