Главная Случайная страница Контакты | Мы поможем в написании вашей работы! | ||
|
В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса.
В отличие от Java, C++ string тип не доступен для всех программ по умолчанию. Если C++ программа требует string тип, программист должен обратиться к библиотеке, которая определяет этот тип. Следующая распечатка иллюстрирует C ++ тип данных последовательности в действии.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: | #include <iostream>#include <string>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { string s1 = "first"; // Initialization string s2; s1 += " string"; // Concatenation s2 = s1; // Assignment cout << s1 << endl; // Stream output cout << s1.length() << endl; // Length return EXIT_SUCCESS;}Listing 3 string variables in use |
1: 2: 3: | // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10]; |
Listing 4 Arrays in Java |
The C++ syntax equivalent to the above Java code looks similar, except for the use of the keyword new. The keyword new, in Java, creates an instance of an object. In C++, the keyword new has a different meaning, one that we address in 1.4.3 Dynamic Memory Management. The following listing demonstrates the declaration of an int array of size ten in C++.
1: 2: | // declare and create an array of integersint cpp_array[10]; |
Listing 5 An array in C++ |
The double bracket ([]) in the declaration indicates that the line declares an array. Notice the placement of the double bracket ([]) in each of the examples. In Java, the double bracket can be placed after the name of the data type or after the name of the variable. In C++, it can only be placed after the name of the variable.
Accessing the elements stored in an array is done the same way in C++ as it is in Java. Both languages use the bracket operator ([]). A programmer encloses in brackets an index number of the element they wish to access. Indexing of arrays in C++, as in Java, begins with zero. This means that the first element of an array is accessed at index 0, the second element at index 1, the third element at index 2, and so on. The following listing demonstrates accessing the elements of a C++ array.
1: 2: 3: | // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10]; |
Listing 4 Arrays in Java |
C++ синтаксис, эквивалентный Java, за исключением использования нового ключевого слова. Новое ключевое слово, в Java, создает объект. В C++, у нового ключевого слова может быть различное значение см. 1.4.3 Dynamic Memory Management. Следующая распечатка демонстрирует объявление массива int в C++.
1: 2: | // declare and create an array of integersint cpp_array[10]; |
Listing 5 An array in C++ |
Двойная скобка ([]) указывает, что в строке объявляется массив. Заметьте размещение двойной скобки ([]) в каждом из примеров. В Java двойная скобка может быть помещена после названия типа данных или после названия переменной. В C++, это может быть помещено только после названия переменной.
Обращение к элементам сохраненных в массиве, в C++ осуществляется аналогично, как и в Java. Оба языка используют оператор двойной скобки ([]). Программист записывает в скобках индекс элемента, означающий величину массива. Индексация массива в C ++, как в Java, начинается с нуля. Это означает, что первый элемент массива всегда имеет индекс 0, второй элемент индекс 1, третий элемент индекс 2, и так далее. Следующая распечатка демонстрирует вызов к элементам массива в C++.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: | #include <iostream>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { int arr[25]; for (int i = 0; i < 25; i++) { arr[i] = i; } cout << "The first element equals: " << arr[0] << endl; cout << "The second element equals: " << arr[1] << endl; cout << "The last element equals: " << arr[24] << endl; return EXIT_SUCCESS;}Listing 6 Accessing elements of a C++ array |
One inherent danger that exists in using C++ arrays is the lack of bounds checking. This is not the case in C++, since boundary checking of arrays is not supported. If we have an array of ten elements in C++, we can attempt to access the 12th, or 20th, or even 100th index of the array. Depending on a few different things, the program may or may not "crash" as a result of our out-of-bounds access. We can be sure, however, that the data we obtain from an out of bounds access will not be meaningful. The following listing shows an out-of-bounds array access in C++.
1: 2: | int arr[10];cout << arr[11] << endl; |
Listing 7 Out of bounds access |
The code in the above listing, in the context of an actual C++ program, definitely compiles, and it may even run without error. This is clearly a dangerous practice, and one that we will always avoid.
Дата публикования: 2014-12-08; Прочитано: 286 | Нарушение авторского права страницы | Мы поможем в написании вашей работы!