Создание новых имен типов данных.

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

typedef type-expression new-name;

Example 1 Usage of typedef

Следующий листинг содержит несколько примеров использования ключевого слова typedef.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <cstdlib> using namespace std; typedef int my_int;typedef my_int* my_int_ptr; int main(int argc, char* argv[]) { my_int i = 10; my_int_ptr ptr = &i; cout << *ptr << endl; return EXIT_SUCCESS;}
Listing 8 A sample use of typedef

Используя названия типа данных, созданные с typedef, позволяют программистам заключать в капсулу свой выбор типов данных. Это - хорошая практика программирования, если вдруг возникает потребность, программист может легко изменить все использование специфического типа данных просто, изменяя определение typedef. Дополнительные возможности использования typedef будут исследованы в 1.5.3 Templates.

1.3.2 Specifying Classes Basic Syntax The class is the basic unit of abstraction in C. Let's look first at a simple class specified in Java, and then the corresponding version in C++. …………………………………………………………………………… The following listing shows the equivalent C++ version of class BankAccount.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: class BankAccount { private: double sum; string name; public: BankAccount(string nm) : name(nm), sum(0) {} double balance() { return sum;} void deposit(double amount) {sum += amount;} void withdraw(double amount) {sum -= amount;} string getName() { return name;}};
Listing 2 A C++ BankAccount class

Access modifiers in C++ do not repeat for each data member. All data members within that section share the access level of the delimiting modifier. In the above listing, everything defined below line 3 and up until the next access modifier in line 7 has private access. Unlike Java, there is no notion of a "public" or "private" class in C++. We cover the various ways of including classes in C++ in page 1.3.4 The Preprocessor.

Another key difference in class specification is that C++ class declarations must end with a semicolon. This semicolon appears in line 14 of the above example.