2: Making & Using Objects

来源:互联网 发布:淘宝网店成功案例 编辑:程序博客网 时间:2024/05/22 08:15

The user-defined data type, or class, is what distinguishes C++ from traditional procedural languages.

Declarations vs. definitions

It's important to understand the difference between declarations and definitions.A declaration introduces a name - an identifier - to the compiler. It tells the compiler "This function or this variable exists somewhere, and here is what it should look like." A definition, on the other hand, says:"make this variable here" or "Make this function here." At the point of definition the compiler allocates storage. For a variable, the compiler determines how big that variable is and causes space to be generated in memory to hold the data for that variable. For a function, the compiler generates code, which ends up occupying storage in memory.

Function declaration syntax

int func1(int a,int b);

A gotcha: There is a significant difference between C and C++ for functions with empty argument lists. In C,the declaration:

int func2();

means "a function with any number and type of argument." This prevents type-checking,so in C++ it meas "a function with no arguments."

Function definitions

int func1(int a,int b){...}

Variable declaration syntax

A variable declaration tells the compiler what a variable looks like. It says,"I know you haven't seen this name before, but I promise it exists someplace, and it's a variable of X type."

int a;

This could declare the variable a as an integer. Here's the conflict: there is enough information in the code above for the compiler to create space for an integer called a, and that's what happens. To resolve this dilemma, a keyword was necessary for C and C++ to say "This is only a declaration; it's defined elsewhere." The keyword isextern. It  can mean the definition is external to the file, or that the definition occurs later in the file. For example:

extern int a;

Including headers

To include a header file, use the #include preprocessor directive. This tells the preprocessor to open the named header file and insert its contents where the#includestatement appears. A #include may name a file in two ways: in angle brackets(<>) or in double quotes. 

File names in angle brackets, such as:

#include <header>
cause the preprocessor to search for the file in a way that is particular to your implementation, but typically there's some kind of "include search path" that you specify in your environment or on the compiler command line.

File names in double quotes, such as:

#include "header.h"
tell the preprocessor search for the file is (according to the specification) an "implementation-defined way." What this typically means is to search for the file relative to the current directory. If the file is not found, then the include directive is reprocessed as if it had angle brackets instead of quotes.

Using the iostream class

The first program uses the concept of standard output, which means "a general-purpose place to send output." The iostream package automatically defines a variable(an object) calledcout(which is short for "console output") that accepts all data bound for standard output.

To send data to standard output, you use the operator <<. C++ allows operators to beoverloaded. When you overload an operator, you give it a new meaning when that operator is used with an object of a particular type.

Namespaces

One of the problems encountered in the C language is that you "run out of names" for functions and identifiers when your programs reach a certain size. More importantly, when a program reaches a certain size it's typically broken up into pieces, each of which is built and maintained by a difference person or group. Since C effectively has a single arena where all the identifier and functions names live, this means that all the developers must be careful not to accidentally use the same names in situations where they can conflict.

Standard C++ has a mechanism to prevent this collision: the namespace keyword. Each set of C++ definitions in a library or program is "wrapped" in a namespace, and if some other definition has an identical name, but is in a different namespace, the there is no collision.

There's a keyword that allows you to say "I want to use the declarations and/or definitions in this namespace." It isusing. All of the Standard C++ libraries are wrapped in a single namespace, which isstd(for "standard").

Reading and writing files

To open files for reading and writing, you must include <fstream>. To open a file for reading, you create anifstream object which then behaves likecin. To open a file for writing, you create anofstream object, which then behaves likecout.

One of the most useful functions in the iostream library is getline(), which allows you to read one line(terminated by a newline) into astring object. The first argument is the ifstream object you're reading from and the second argument is thestring object. When the function call is finished, thestring object will contain the line.getline() reads in the characters of each line untile it discovers a newline. However, it discards the newline and doesn't store it in the resulting string object.

The next program uses ifstream and ofstream to read from file and send the data to another file.

//============================================================================// Name        : ACM.cpp// Author      : Moment// Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include<iostream>#include<fstream>#include<vector>#include<string>using namespace std;int main(){vector<string> lines;string str;ifstream in("a.in");ofstream out("b.out");while(getline(in,str))lines.push_back(str);for(unsigned i = 0;i < lines.size();i++)out << i << ": " << lines[i] << "\n";return 0;}

原创粉丝点击