рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Assessments

Assessments - раздел Философия, Data Structures and Algorithms in C++ · Multiple-Choice Quiz 1 Recommended Exercise 1 ...

· Multiple-Choice Quiz 1

  • Recommended Exercise 1
1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C++ categorizes data objects into different types. These different data types describe not only the fundamental operations that the language performs on the data, but also the range of values that the data types accept. Since different data types have different allowable values, the language can check to ensure that a programmer only assigns appropriate values to a data object. An error occurs if a programmer assigns an inappropriate value, such as a number that is too large or too small, to a data object. This mechanism is known as type checking. C++ is considered a strongly typed language since it is very strict about checking data types and their corresponding values. In the end, this is good for the C++ programmer, since strongly typed languages can detect errors that other languages may not detect. The fundamental data types that C++ supports are similar to the primitive data types of Java. The following table lists each of the fundamental data types of C++ and the corresponding Java primitive data type. 1.3.1 Data Types Fundamental Data Types   Типы данных описывают не только фундаментальные операции, но также диапазон значений, которые принимают типы данных. Так как у различных типов данных различен диапазон значений, язык программирования предоставляет возможность проверить соответствующее значение объекта данных. Ошибка возникает, если только целому числу присвоят значение слишком большое или слишком маленькое. Этот механизм известен как проверка типа. Он позволяет обнаружить ошибки, которые, возможно, не обнаруживаются в других языках программирования. В C++ фундаментальные типы данных подобны типам данных Java. Следующая таблица представляет фундаментальные типы данных в C++ и соответствующие им тип данных в Java.
C++ type Java type     Table 1 C++ and Java data types
bool boolean
char char
int int
short short
long long
float float
double double

 

The space required to store variables differs across languages. In C++, the storage space requirements are left to the discretion of the compiler implementers. Unlike Java, these requirements are not specifically stated by the language standard. Therefore, on one platform a C++ int may be two bytes long, while on another it may be four bytes long. But, in Java, a variable of type int is guaranteed to require four bytes of memory to store. Usually, the size in bytes of a variable is unimportant, except that it dictates the range of values that a variable can accept. As the number of bytes that a language implementation uses to store a variable increases, so does the range of values that the variable accepts. The following example program uses the C++ sizeof operator to display the size, in bytes, of the fundamental data types of the particular C++ implementation used in В C++ место хранения данных в памяти определяется конструктором компилятора. В Java, эти требования не требуют какого либо указания. Поэтому в C++ int может быть длиной как два так и четыре байта. В Java же переменная типа int всегда равна длине памяти в четыре байта. Размер в байтах незначителен, за исключением того, что он диктует диапазон значений, которые может принять переменная.   Следующая программа в C++ качестве примера использует оператор sizeof, чтобы показать размер, в байтах, фундаментальных типов специфических данных в C++, используемое в компиляции при выполнении.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: #include <cstdlib>#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << " bool: " << sizeof(bool) << endl; cout << " char: " << sizeof(char) << endl; cout << " short: " << sizeof(short) << endl; cout << " int: " << sizeof(int) << endl; cout << " long: " << sizeof(long) << endl; cout << " float: " << sizeof(float) << endl; cout << "double: " << sizeof(double) << endl; return EXIT_SUCCESS;} Listing 1 Data types and the sizeof operator
 

 

Like Java, C++ contains a mechanism to create "read-only" variables. C++ uses the keyword const to allow programmers to create "read-only" variables. This keyword signals that the variable being declared cannot be modified after it is initialized. The keyword const of C++ is analogous to the keyword final in Java. Listing 2 shows the declaration and initialization of some "read-only" variables, otherwise simply known as "constant variables" or just "constants."
1: 2: 3: const int BOILING_POINT = 100;const int FREEZING_POINT = 0;const float PI = 3.14159;
Listing 2 Constant variables

– Конец работы –

Эта тема принадлежит разделу:

Data Structures and Algorithms in C++

Compiling and Running a C Program C Background History C is a modern object oriented programming language that supports... Table Different problems with similar solutions Each of the problems... Vectors...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Assessments

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Strings
In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. The Java counterpart is actually two separate classes. Unlike its J

Strings
В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса. В отличие от Ja

Creating New Data Type Names
It is possible in C++ for a programmer to create additional names for existing data types. Creating another name uses the keyword typedef. The syntax to create a new name is as follows. typed

Создание новых имен типов данных.
В C++ есть возможность создать дополнительно к существующим собственные типы данных с новым именем. Для этого необходимо использовать ключевое слово typedef. Синтаксис, чтобы создать новое имя след

Constructors
Constructors are the methods of a class that define what actions to take when creating an object. A C++ class can have multiple constructors. This allows variation in object instantiation since dif

The Destructor
A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object

Declaration vs. Definition
In this discussion on the specification of classes in C++, the term "definition" has been used regarding functions. When we "define" a function, we dictate the function's behavi

Basic Syntax
Класс - основная единица абстракции в C++. Давайте сначала рассмотрим простой класс, определенный в Java, и затем соответствующую версию в C++. ………………………………………………………………………………… Сле

Constructors
Конструктор создает и инициализирует новый экземпляр класса. В C++ класс может иметь несколько конструкторов. Это позволяет вносить изменение в экземпляры класса включая типы параметров и значения,

Declaration vs. Definition
В обсуждении о спецификации классов, термин "definition" ("определение") был использован относительно функции. Когда мы "definition" функцию, мы определяем поведение ф

Streams
Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time,

Using the Standard Streams
Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams h

File Input and Output
File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program

Some Common Pitfalls
  A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You alwa

Streams
Ввод и вывод в C ++ основан на понятии потока. Поток - последовательность байтов, которые вытекают из одного в другое. Процесс продукции вовлекает байты, по одному, с программы на устройство. Это у

Using the Standard Streams
Три определенных потока всегда доступны всюду в C ++ программах. Это standard input, standard output, and standard error потоки. У каждого из этих стандартных потоков есть определенное использовани

File Input and Output
Файл вход и выход подобен механизмам для ввода / вывода экрана и клавиатуры. Главное различие - то, что программисты должны явно открыть и закрыть файлы. В псевдокоде главная программа, которая чит

Some Common Pitfalls
Частая ошибка для многих новых C ++ программисты состоит в том, чтобы полностью изменить << и >> операторы. Хороший способ помнить, какой оператор использовать должен думать о них как о

Text Substitution
The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and

File Inclusion
File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can onl

Macro Substitution
The C++ preprocessor can perform a programmer defined text substitution throughout an entire source code file. This is known as macro substitution. Programmers define a macro using the #define prep

Conditional Compilation
Beyond macro substitution, a more important reason to use #define is to support conditional compilation. Using #define, and some other preprocessor directives, we can instruct the compiler to compi

An Example: Assumption Verification
Verifying assumptions using assertions is an example of a common use of the preprocessor and its features. An assertion is a statement placed in source code to verify an assumption. Usually, progra

Text Substitution
Препроцессор это инструмент, чтобы управлять содержанием файлов исходного текста до компиляции. В самом общем смысле препроцессор выполняет текстовую замену и текстовую модификацию. Высокоуровневые

File Inclusion
Включение файла - особенность C++ препроцессор, который позволяет файлу исходного текста использовать разделенные коды. Мы полагаем, что разделенный код это классы или функции, объявленные в других

Macro Substitution
C++ препроцессор может определить текстовую замену всюду по всему файлу исходного текста. Это известно как макро-замена. Программисты реализуют макро-замену директивой #define препроцессора, котора

Conditional Compilation
Вне макро-замены важная причина использовать #define состоит в том, чтобы поддержать условную трансляцию. Используя #define, и некоторые другие директивы препроцессора, мы можем проинструктировать

An Example: Assumption Verification
Подтверждение предположений, используя утверждения является примером обычного использования препроцессора и его особенностей. assertion - утверждение, помещенное в исходный текст, чтобы проверить п

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги