Вы находитесь на странице: 1из 14

Microsoft Visual C++ .

NET Step by Step - Version 2003


by Julian Templeman and Andy Olsen
Microsoft Corporation. (c) 2003. Copying Prohibited.

Reprinted for Tran Minh Thai, TMT


minhthai@live.com

Reprinted with permission as a subscription benefit of Books24x7,


http://www.books24x7.com/

All rights reserved. Reproduction and/or distribution in whole or in part in


electronic,paper or other forms without written permission is prohibited.
i

Table of Contents
Chapter 1: Hello, C++!.....................................................................................................................1
Overview................................................................................................................................1
What Is a C++ Program?.......................................................................................................1
C++ is a strongly typed language.....................................................................................1
C++ is an efficient language.............................................................................................1
C++ is an object-oriented language.................................................................................1
C++ is based on C (as you might suspect)......................................................................1
C++ is a case-sensitive language....................................................................................2
Your First C++ Program.........................................................................................................2
The main Function...........................................................................................................3
C++ Keywords and Identifiers..........................................................................................3
Creating an Executable Program—Theory............................................................................4
Editing the Program Source Files....................................................................................4
Compiling the Source Files..............................................................................................4
Linking the Object Files....................................................................................................5
Running and Testing the Program...................................................................................5
Creating an Executable Program—Practice..........................................................................5
Adding a C++ Source File to the Project..........................................................................8
Adding C++ Code to the Source File...............................................................................9
Building the Executable..................................................................................................10
Executing the Program...................................................................................................11
Conclusion...........................................................................................................................11
Chapter 1 Quick Reference.................................................................................................12
Chapter 1: Hello, C++!
Overview
In this chapter, you will learn how to:

• Recognize C++ characteristics

• Recognize C++ functions

• Recognize C++ keywords and identifiers

• Create a C++ program

Welcome to the exciting world of programming .NET with Microsoft Visual C++. This chapter
introduces the C++ language and simple input/output (I/O) using the C++ standard library console
(text-based) facilities.

What Is a C++ Program?


Well, it contains exactly the same elements as any other computer program— data to store your
information and blocks of code that manipulate that data. Whether your previous experience is with
Microsoft Visual Basic or with 40- year-old COBOL, the basic elements will be familiar. Much
mystery surrounds the practice of C++ programming, but most of it is unwarranted and
unnecessary. Let’s start with some basic ground rules for C++.

C++ is a strongly typed language.


If you have a variable that has been declared able to store apples, you can store only apples in it.
However, this requirement is not as grim as it sounds. C++ contains many features for providing
implicit conversions where necessary. This strong type checking eliminates many common
programming bugs because it explicitly disallows any data type conversions that could result in data
loss.

C++ is an efficient language.


If you write code that needs to execute quickly (for example, code that sorts lists or performs
complex mathematics), C++ should be your language of choice.

C++ is an object-oriented language.


Modern programmers like the many advantages of object-oriented programming. (See Chapter 2 for
more information on object-oriented programming.) C++ is one of the premier object-oriented
programming languages.

C++ is based on C (as you might suspect).


C is a well-established language. Although C++ includes some strange features—to maintain its
compatibility with C—it probably wouldn’t be as popular as it is without C compatibility.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 2

C++ is a case-sensitive language.


If the compiler warns you about an undeclared variable, you probably typed an uppercase character
instead of a lowercase character (or vice versa).

Your First C++ Program


Let’s get our hands dirty with a simple C++ program. Of course, no book on C++ would be complete
without including the clichéd Hello, World program, so let’s start with that.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello, World!" << endl;
return 0;
}

This short program illustrates some fundamental C++ concepts:

• The first line uses the directive #include to tell the C++ compiler to copy in the file named
iostream at the beginning of the program. Why is this inclusion necessary? A golden rule of
C++ is that everything must be declared before it is used, including the output stream named
cout used later in the program. (The cout output stream causes output to go to the console.)
So why not just declare cout explicitly in this file? Because the iostream file is a separate
unit, it can be included in any other program, thus making it easy to reuse the declarations.
In a nutshell, this file saves a lot of typing for the programmer.

• The second line (which begins with using) tells the compiler that the standard C++ library is
to be used (hence the word std—an abbreviation of standard). Many different libraries could
be used in a single project; the using statement lets us tell the compiler which library we
mean to use.

• The rest of the program is an example of a C++ function. All blocks of code in C++ are called
functions—there’s no such thing as a procedure or a subroutine. Each C++ function contains
the header (the first line of this program) and the function body (all of the text between the
braces { and }). The header shows the return value of the function (in this case int, short for
integer), the name of the function (main), and the list of parameters inside round brackets.
This example has no parameters, so the round brackets are empty—but the brackets still
must be there.

• All statements in C++ are terminated with a semicolon.

Of the seven lines of text in the example program, only two contain C++ statements: the cout line
and the return line. The cout line outputs characters to the console. The syntax for using cout is the
word cout followed by a << operator, followed by the items you want to output. (The endl stream
manipulation operator inserts a new-line character in the stream.)

You can output many items by using a single cout statement—just separate any extra items with
further << operators, as shown here:
cout << "Hello" << ", " << "World" << endl;

Alternatively, you can use several cout statements to give exactly the same effect:

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 3

cout << "Hello";


cout << ", ";
cout << "World";
cout << endl;

As you might expect, programmers tend to prefer the single-statement version.

The main Function


Why is this example’s only function named main? The simple answer is that the example won’t
compile if the function isn’t named main. However, it might be more useful to explain how the
language works.

A normal C++ program contains many functions (and also many classes, as discussed in Chapter
2). How does the compiler know which function should be called first? Obviously, the compiler can’t
be allowed to just randomly choose a function! The rule is that the compiler will always generate
code that looks for a function named main. If you omit the main function, the compiler reports an
error and doesn’t create a finished executable program.

Free-Format Languages

The C++ language is free-format, which means that the compiler ignores all spaces, carriage
returns, new-line characters, tabs, form feeds, and so on. Collectively, these characters are referred
to as white space. The only time the compiler recognizes white space is if it occurs inside a string.

Free-format languages give the programmer great scope for using tab or space indenting as a way
of organizing program layout. Statements inside a block of code—such as a for loop or an if
statement—are typically indented slightly (often four characters). This indentation helps the
programmer’s eye more easily pick out the contents of the block.

The free-format nature of C++ gives rise to one of the most common (and least useful) arguments in
the C++ community—how do you indent the braces? Should they be indented with the code, or
should they be left hanging at the beginning of the if or the for statement? There is no right or wrong
answer to this question (although some hardened C++ developers might disagree), but a consistent
use of either style will help make your program readable. As far as the compiler is concerned, your
entire program could be written on one line!

So the compiler will expect a function named main. Is that all there is to it? Well, not quite. There
are some additional items—such as the return type and parameters being correct—but in the case
of main, some of the C++ rules are relaxed. In particular, main can take parameters that represent
the command-line arguments, but you can omit them if you don’t want to use the command line.

C++ Keywords and Identifiers


A C++ keyword (also called a reserved word) is a special item of text that the compiler expects to be
used in a particular way. The keywords used in the example program are using, namespace, and
return. You’re not allowed to use these keywords as variable or function names—the compiler will
report an error if you do.

An identifier is any name that the programmer uses to represent variables and functions. An
identifier must start with a letter and must contain only letters, numbers, or underscores. The
following are legal C++ identifiers:

• My_variable

• AReallyLongName

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 4

The following are not legal C++ identifiers:

Identifier Reason for Being Invalid


0800Number Must not start with a number
You+Me Must contain only letters, numbers, and underscores
return Must not be a reserved word

Compiler Error or Linker Error?

To be absolutely correct, it is the linker that reports the error. You’ll find more on compiler and linker
errors later in this chapter.

Outside of these restrictions, any identifier will work. (Oddly enough, the identifier main is not a
reserved keyword; you can define a variable named main within the program—but this is not
recommended!) Some choices are not recommended. For example:

Identifier Reason It’s Not Recommended


main Could be confused with the function main.
INT Too close to the reserved word int.
B4ugotxtme Just too cryptic!
_identifier1 Underscores at the beginning of names are allowed, but they
are not recommended because compilers often use leading
underscores when creating internal variable names, and they
are also used for variables in system code. To avoid potential
naming conflicts, you should not use leading underscores.

Creating an Executable Program—Theory


Several stages are required to build an executable program; Microsoft Visual Studio .NET helps by
automating them. To examine and understand these stages, however, let’s look at them briefly.
You’ll see these stages again later in the chapter when we build our first program.

Editing the Program Source Files


Before you can create a program, you must write something! Visual Studio .NET provides an
integrated C++ editor, complete with color syntax highlighting and Microsoft IntelliSense to show
function parameter information and word completion.

Compiling the Source Files


The C++ compiler is the tool for converting textual source files into machine code object files that
have an .obj file extension. (Object in this sense is not to be confused with object-oriented.) The
compiler is invoked inside the Visual Studio .NET environment, and any errors or warnings are
displayed in the environment.

However, the object files produced are not executable files. They are incomplete, lacking references
to any functions not contained with the source files for the particular compilation.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 5

Linking the Object Files


The final step in producing an executable file is to link together all object files that make up a
particular project. This linking includes not only object files produced from your own source code,
but also object files from system libraries such as the C++ standard library or the Microsoft
Foundation Class (MFC) library.

Link errors tend to be less helpful than compile errors. Compile errors will give the file name and the
line number of the error; the linker will give only the name of the object file, so a bit of detective work
is often required.

System and Class Libraries

System and class libraries often have many .obj files associated with them. Handling all of a
library’s object files in a project would soon become onerous, so .obj files are frequently combined
into .lib library files for convenience.

Running and Testing the Program


Although linking might be the final step in creating an executable file, it’s not the last step in
development. You still need to run and test the program.

For many development environments, running and testing is often the most difficult part of the
program development cycle. However, Visual Studio .NET has yet another ace up its sleeve—the
integrated debugger. The debugger has a rich set of features to allow easy run-time debugging,
such as setting breakpoints and variable watches.

Creating an Executable Program—Practice


• Start up Microsoft Visual Studio .NET. An invitingly blank window should be displayed.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 6

• This window is the powerful Visual Studio .NET integrated development environment (IDE).
It contains all the tools you’ll need to create full-featured, easy-to-use applications.

Creating a Project

The first task is to create a new project for the Hello, World program. To create a project, follow
these steps:

1. Under the File menu, point to New, and then click Project. (Alternatively, you can press
Ctrl+Shift+N.)

The New Project dialog box will be displayed.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 7

2. Select Visual C++ Projects in the Project Types pane, select Win32 Console Project in the
Templates pane, and then type HelloWorld in the Name text box.

3. Choose a location for your new project in the Location combo box, either by typing a
directory path in the Location combo box or by clicking Browse and navigating to the
appropriate directory.

4. Click OK to start the Win32 Application Wizard.

This project will possess a simple, text-based interface (similar to an MS-DOS screen from
years ago) that will be adequate for our purposes. Before proceeding, though, you need to
change one setting.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 8

5. Click the Application Settings text on the left side of the dialog box. The right side of the
dialog box changes to show the current wizard settings.

6. Select Empty Project under Additional Options.

7. Click Finish to create the project.

The wizard correctly initializes all the compiler settings for a console project.

Adding a C++ Source File to the Project


An empty project is not particularly exciting on its own, so let’s add a new C++ source file. As
always in Visual Studio .NET, you have many ways to do the same thing.

1. Either right-click the Hello World icon in Solution Explorer, point to Add, and then click Add
New Item, or click the Add New Item button on the toolbar.

Either action will open the Add New Item dialog box.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 9

2. Select C++ File (.cpp) from the Templates pane on the right, type HelloWorld.cpp in the
Name text box, and then click Open.

Visual Studio .NET creates an empty source code file and adds it to the project for you.

Now it’s time to put the mouse down, pick up the keyboard, and start typing some C++ code.

Adding C++ Code to the Source File


Type in the source code for the program, as shown here.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 10

Notice that the keywords automatically turn blue (provided that you spell them correctly).

Building the Executable


The next step is to build the executable. The term build in Visual Studio .NET refers to compiling
and linking the program. Visual Studio .NET compiles any source files that have changed since the
last build and—if no compile errors were generated—performs a link.

To build the executable, select Build Solution from the Build menu or press Ctrl+Shift+B. An Output
window displaying the build progress will appear near the bottom of the Visual Studio .NET window.
If no errors are encountered, the message Build: 1 succeeded, 0 failed, 0 skipped should appear in
the Output window.

If any problems occur, the Output window will contain a list of errors and warnings, as shown here.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 11

If the error or warning is generated by the compiler and not the linker, double-click the error line in
the Output window to place the cursor at the line in the source file where the compiler encountered
the error. Fix the error (you might have misspelled a keyword or forgotten a semicolon), and rebuild
the project.

How Should You Treat Warnings?

Always treat warnings as errors—in other words, get rid of them. Warnings are there for a
reason—they mean your code is not correct.

Executing the Program


Once you’ve eliminated all errors and you’ve successfully built the project, you can finally execute
the program. Choose Start Without Debugging from the Debug menu to run the program. You can
also press CTRL+F5 to execute the program.

You’ll see the output of your program, with a line at the bottom of the output telling you to “Press
any key to continue”. This line is added by the IDE so that the console window doesn’t simply
disappear when the program has finished running.

Conclusion
Although the example in this chapter isn’t the most exciting program ever written, it demonstrates
some key C++ development points. It introduces the Visual Studio .NET IDE and the ability to
compile and link a program, and it serves as an introduction to the C++ language.

Now there’s no turning back. Every new C++ and Visual Studio .NET feature that you learn about
will fire your imagination to learn more and be productive. Software development can be an exciting
world.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited
Microsoft Visual C++ .NET Step by Step - Version 2003 12

Finally, don’t forget to have some fun. Go back and try a few variations on the example program,
click a few menus, and become familiar with the environment. You have nothing to lose.

Chapter 1 Quick Reference


To Do this
Create a new project in Visual Studio .NET. Use the File, New, Project menu item, or press
Ctrl+Shift+N.
Add a file to a project. Use the File, New, File menu item, or press
Ctrl+N.
Build a Visual Studio .NET project. Use the Build, Build Solution menu item, or press
Ctrl+Shift+B.
Execute a program from within Visual Studio Use the Debug, Start Without Debugging menu
.NET. item, or press Ctrl+F5.

Reprinted for minhthai, TMT Microsoft Press, Microsoft Corporation (c) 2003, Copying Prohibited

Вам также может понравиться