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

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

Declaration vs. Definition

Declaration vs. Definition - раздел Философия, Data Structures and Algorithms in C++ In This Discussion On The Specification Of Classes In C++, The Term "def...

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 behavior through the code that exists within the curly braces. The "declaration" of a function, on the other hand, only specifies the interface of the function. This interface includes the function name, the return type, and the list of parameters and their types. The following listing shows both a declaration and definition of the function average.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: #include <iostream>#include <cstdlib> using namespace std; // function declarationdouble average(int, int); int main(int argc, char* argv[]) { cout << average(10, 2) << endl; return EXIT_SUCCESS;} // function definitiondouble average(int total, int count) { return (total / count);}
Listing 6 Declaration vs. definition

The declaration and definition of a function differ in many aspects. In the above example, notice the declaration of function average is followed by a semi-colon and not by curly braces. This specifies that it is the declaration, not the definition. A function declaration does not need to include variable names for the parameters. The definition, on the other hand, looks just the same as any C++ function we have seen so far. It is interesting to note that the definition of the function comes after its actual use in function main. This is acceptable since we placed a declaration of the function prior to function main. This practice, known as a forward reference, is common in C++ programming. It is legal to use a function or a class that is not yet defined, as long as it has been declared. It is illegal, however, to use a function or a class that is not yet defined without including the forward reference.

The rules regarding class specification in C++ offer some flexibility in the placement of member function definitions. A C++ class can include all its member function definitions inside of the class definition. This is the approach taken in the examples we have seen so far. Alternatively, the definitions for one or more class member functions can appear outside the class definition, as long as we still include the declarations inside the class definition.

Programmers must fully qualify the names of class member functions that appear outside of a class definition. To qualify a name fully, the function name must be prepended with the class name followed by the scope resolution operator (::). Listing 7 defines class member functions outside the class definition.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: class BankAccount { private: double sum; string name; public: BankAccount(string nm) : name(nm), sum(0) {} BankAccount(string nm, double bal) : name(nm), sum(bal) {} double balance(); void deposit(double); void withdraw(double); string getName();}; double BankAccount::balance() { return sum;}void BankAccount::deposit(double amount) { sum += amount;}void BankAccount::withdraw(double amount) { sum -= amount;}string BankAccount::getName() { return name;}
Listing 7 Defining class member functions outside the declaration

Placing class member function definitions outside the class definition has benefits. First, it reduces the size of the class definition. This enhances readability, since it becomes easier to view the entire class interface when the function definitions appear elsewhere.

Separating member function definitions from their declarations also allows the sharing of precompiled code. Listing 7 shows class member function definitions that appear outside their class definition. These definitions still appear in the same file as the class definition. Class member-function definitions can also appear in an altogether different file than the class definition. When a programmer specifies a class in this manner, the programmer can compile the file that contains the class member-function definitions. This file containing the class member-function definitions is known as an implementation file. The class definition file (or header file) then becomes the interface that shares the precompiled code.

Listing 8 shows the definition file bankaccount.h:

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: #include <string>#include <cstdlib>#include <iostream> #ifndef _BANKACCOUNT_H#define _BANKACCOUNT_H using namespace std; class BankAccount { private: double sum; string name; public: BankAccount(string nm) : name(nm), sum(0) {} BankAccount(string nm, double bal) : name(nm), sum(bal) {} double balance(); void deposit(double); void withdraw(double); string getName();}; #endif
Listing 8 bankaccount.h    

Listing 9 shows the implementation file bankaccount.cpp:

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: #include "bankaccount.h" double BankAccount::balance() { return sum;}void BankAccount::deposit(double amount) { sum += amount;}void BankAccount::withdraw(double amount) { sum -= amount;}string BankAccount::getName() { return name;}
Listing 9 bankaccount.cpp

The preprocessor directive #include replace the directive with the contents of the specified file. The directives #define, #ifndef and #endif are used to check if a definition file is not included more than once. We examine the uses of preprocessor directives in page 1.3.4 The Preprocessor.

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

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

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...

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

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

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

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

Assessments
· Multiple-Choice Quiz 1 Recommended Exercise 1 1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C+

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

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
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги