Tải bản đầy đủ (.pdf) (13 trang)

Giới thiệu tỏng quát ngôn ngữ C++ bằng Tiếng Anh và Tiếng Việt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (875.46 KB, 13 trang )

1.2 Programs
C++ is a compiled language. For a program to run, its source text has to be processed by a
compiler, producing object files, which are combined by a linker yielding an executable
program. A C++ program typically consists of many source code files (usually simply
called source files).

An executable program is created for a specific hardware/system combination; it is not
portable, say, from a Mac to a Windows PC. When we talk about portability of C++
programs, we usually mean portability of source code; that is, the source code can be
successfully compiled and run on a variety of systems.
The ISO C++ standard defines two kinds of entities:

● Core language features, such as built-in types (e.g., char and int) and loops (e.g.,
for-statements and while-statements)

● Standard-library components, such as containers (e.g.,

vector and map) and I/O

operations (e.g., << and getline())
The standard-library components are perfectly ordinary C++ code provided by every C++
implementation. That is, the C++ standard library can be implemented in C++ itself and
is (with very minor uses of machine code for things such as thread context switching).
This implies that C++ is sufficiently expressive and efficient for the most demanding
systems programming tasks.
C++ is a statically typed language. That is, the type of every entity (e.g., object, value,
name, and expression) must be known to the compiler at its point of use. The type of an
object determines the set of operations applicable to it.

1.2.1 Hello, World!
The minimal C++ program is




1.2 Chương trình
C++ là một ngơn ngữ biên dịch. Để một chương trình có thể chạy, văn bản nguồn của nó
phải được trình biên dịch xử lý, tạo ra các tệp đối tượng, được kết hợp bởi một trình liên
kết để tạo ra một chương trình thực thi. Một chương trình C++ thường bao gồm nhiều tệp
mã nguồn (thường được gọi đơn giản là tệp nguồn).

Một chương trình thực thi được tạo cho một tổ hợp phần cứng/hệ thống cụ thể; nó khơng
thể di động từ máy Mac sang PC chạy Windows. Khi chúng ta nói về tính di động của các
chương trình C++, chúng ta thường muốn nói đến tính di động của mã nguồn; nghĩa là mã
nguồn có thể được biên dịch thành công và chạy trên nhiều hệ thống khác nhau.
Tiêu chuẩn ISO C++ xác định hai loại thực thể:


Các tính năng ngơn ngữ cốt lõi, chẳng hạn như các kiểu tích hợp sẵn (ví dụ: char và
int) và các vịng lặp (ví dụ: câu lệnh for và câu lệnh while)



Các thành phần thư viện tiêu chuẩn, chẳng hạn như vùng chứa (ví dụ: vector và
map) và hoạt động I/O (ví dụ: << và getline())

Các thành phần thư viện tiêu chuẩn là mã C++ hồn tồn bình thường được cung cấp bởi
mọi quá trình triển khai C++. Có nghĩa là, thư viện chuẩn C++ có thể được thực hiện bằng
chính C++ và là (với việc sử dụng rất nhỏ mã máy cho những thứ như chuyển đổi ngữ cảnh
luồng). Điều này ngụ ý rằng C++ đủ biểu đạt và hiệu quả cho các tác vụ lập trình hệ thống
địi hỏi khắt khe nhất.
C++ là một ngơn ngữ được định kiểu tĩnh. Nghĩa là, loại của mọi thực thể (ví dụ: đối
tượng, giá trị, tên và biểu thức) phải được trình biên dịch biết tại thời điểm sử dụng của nó.

Loại đối tượng xác định tập hợp các hoạt động áp dụng cho nó.

1.2.1 Hello, World!
Chương trình C++ tối thiểu là


int main() { } // the minimal C++ program

This defines a function called main, which takes no arguments and does nothing. Curly
braces, { }, express grouping in C++. Here, they indicate the start and end of the function
body. The double slash, //, begins a comment that extends to the end of the line. A comment
is for the human reader; the compiler ignores comments.
Every C++ program must have exactly one global function named main(). The program
starts by executing that function. The int integer value returned by main(), if any, is the
program’s return value to ‘‘the system.’’ If no value is returned, the system will receive a
value indicating successful completion. A nonzero value from main() indicates failure. Not
every operating system and execution environment make use of that return value:
Linux/Unix-based environments do, but Windows based environments rarely do.
Typically, a program produces some output. Here is a program that writes Hello, World!:
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
}

The line #include <iostream> instructs the compiler to include the declarations of the
standard stream I/O facilities as found in iostream. Without these declarations, the
expression
std::cout << "Hello, World!\n"


would make no sense. The operator << (‘‘put to’’) writes its second argument onto its first.
In this case, the string literal "Hello, World!\n" is written onto the standard output stream
std::cout. A string literal is a sequence of characters surrounded by double quotes. In a
string literal, the backslash character \ followed by another character denotes a single
‘‘special character.’’ In this case, \n is the newline character, so that the characters written
are Hello, World! followed by a newline.
The std:: specifies that the name cout is to be found in the standard-library namespace
(§3.4). I usually leave out the std:: when discussing standard features; §3.4 shows how to
make names from a namespace visible without explicit qualification.
Essentially all executable code is placed in functions and called directly or


int main() { }

// the minimal C++ program

Điều này xác định một hàm được gọi là main, khơng có đối số và khơng làm gì cả.
Dấu ngoặc nhọn, { }, phân nhóm thể hiện trong C++. Ở đây, chúng chỉ ra điểm bắt đầu
và kết thúc của thân hàm. Dấu gạch chéo kép, //, bắt đầu một nhận xét kéo dài đến cuối
dịng. Một bình luận là dành cho người đọc; trình biên dịch bỏ qua các bình luận.
Mỗi chương trình C++ phải có đúng một hàm tồn cục có tên là main(). Chương trình
bắt đầu bằng cách thực hiện chức năng đó. Giá trị số nguyên int được trả về bởi main(), nếu
có, là giá trị trả về của chương trình cho ‘‘hệ thống.’’ Nếu khơng có giá trị nào được trả về,
hệ thống sẽ nhận một giá trị cho biết đã hồn thành thành cơng. Giá trị khác không từ hàm
main() cho biết lỗi. Không phải mọi hệ điều hành và môi trường thực thi đều sử dụng giá
trị trả về đó: Mơi trường dựa trên Linux/Unix thì làm được, nhưng môi trường dựa trên
Windows hiếm khi làm được.
Thơng thường, một chương trình tạo ra một số đầu ra. Đây là một chương trình viết Hello,
World!:
#include <iostream>

int main()
{
std::cout << "Hello, World!\n";
}

Dịng #include <iostream> hướng dẫn trình biên dịch bao gồm các khai báo của cơ sở I/O
luồng tiêu chuẩn như được tìm thấy trong iostream. Nếu khơng có các khai báo này, biểu
thức
std::cout << "Hello, World!\n";

sẽ khơng có ý nghĩa. Toán tử << (‘‘đặt vào’’) ghi đối số thứ hai lên đối số thứ nhất. Trong
trường hợp này, chuỗi ký tự "Hello, World!\n" được viết vào luồng đầu ra tiêu chuẩn
std::cout. Một chuỗi ký tự là một chuỗi các ký tự được bao quanh bởi dấu ngoặc kép. Trong
một chuỗi ký tự, ký tự gạch chéo ngược \ theo sau là một ký tự khác biểu thị một ‘‘ký tự
đặc biệt’’. Trong trường hợp này, \n là ký tự dịng mới, do đó các ký tự được viết là Hello,
World! theo sau là một dòng mới.
std:: chỉ định rằng tên cout sẽ được tìm thấy trong khơng gian tên thư viện chuẩn (§3.4).

Tơi thường bỏ qua std:: khi thảo luận về các tính năng tiêu chuẩn; §3.4 chỉ ra cách hiển thị
tên từ không gian tên mà không cần trình độ rõ ràng.


Về cơ bản, tất cả mã thực thi được đặt trong các hàm và được gọi trực tiếp hoặc gián


indirectly from main(). For example:
#include <iostream> // include (‘‘import’’) the declarations for the I/O stream library
using namespace std;

// make names from std visible without std:: (§3.4)


double square(double x)
{
return x∗x;
}

// square a double precision floating-point number

void print_square(double x)
{
cout << "the square of " << x << " is " << square(x) << "\n";
}
int main()
{
print_square(1.234);
}

// print: the square of 1.234 is 1.52276

A ‘‘return type’’ void indicates that a function does not return a value.

1.3 Functions
The main way of getting something done in a C++ program is to call a function to do it.
Defining a function is the way you specify how an operation is to be done. A function
cannot be called unless it has been previously declared.
A function declaration gives the name of the function, the type of the value returned (if
any), and the number and types of the arguments that must be supplied in a call. For
example:
Elem∗ next_elem();
void exit(int);

double sqrt(double);

// no argument; return a pointer to Elem (an Elem*)
// int argument; return nothing
// double argument; return a double

In a function declaration, the return type comes before the name of the function and the
argument types come after the name enclosed in parentheses.
The semantics of argument passing are identical to the semantics of initialization
(§3.6.1). That is, argument types are checked and implicit argument type conversion takes
place when necessary (§1.4). For example:


double s2 = sqrt(2); // call sqrt() with the argument double{2}


tiếp từ hàm main(). Ví dụ:
#include <iostream> // include (‘‘import’’) the declarations for the I/O stream library
using namespace std;

// make names from std visible without std:: (§3.4)

double square(double x)
{
return x∗x;
}

// square a double precision floating-point number

void print_square(double x)

{
cout << "the square of " << x << " is " << square(x) << "\n";
}
int main()
{
print_square(1.234);
}

// print: the square of 1.234 is 1.52276

‘‘Kiểu trả về’’ void chỉ ra rằng một hàm không trả về giá trị.

1.3 Các hàm
Cách chính để hồn thành một việc gì đó trong chương trình C++ là gọi một hàm để thực
hiện nó. Định nghĩa một hàm là cách bạn chỉ định cách thực hiện một hoạt động. Một hàm
khơng thể được gọi trừ khi nó đã được khai báo trước đó.
Một khai báo hàm cung cấp tên của hàm, kiểu của giá trị được trả về (nếu có), số lượng
và kiểu của các đối số phải được cung cấp trong một lệnh gọi. Ví dụ:
Elem∗ next_elem();
void exit(int);
double sqrt(double);

// no argument; return a pointer to Elem (an Elem*)
// int argument; return nothing
// double argument; return a double

Trong một khai báo hàm, kiểu trả về đứng trước tên của hàm và kiểu đối số đứng sau tên
được đặt trong dấu ngoặc đơn.
Ngữ nghĩa của việc truyền đối số giống với ngữ nghĩa của q trình khởi tạo (§3.6.1).
Nghĩa là, các kiểu đối số được kiểm tra và việc chuyển đổi kiểu đối số ngầm định diễn ra

khi cần thiết (§1.4). Ví dụ:


double s2 = sqrt(2);

// call sqrt() with the argument double{2}

double s3 = sqrt("three");

// error: sqrt() requires an argument of type double

The value of such compile-time checking and type conversion should not be
underestimated. A function declaration may contain argument names. This can be a help
to the reader of a program, but unless the declaration is also a function definition, the
compiler simply ignores such names. For example:
double sqrt(double d);
double square(double);

// return the square root of d
// return the square of the argument

The type of a function consists of its return type and the sequence of its argument types.
For example:
double get(const vector<double>& vec, int index);
, int)

// type: double(const vector<double>&

A function can be a member of a class (§2.3, §4.2.1). For such a member function, the
name of its class is also part of the function type. For example:

char& String::operator[ ](int index);

// type: char& String::(int)

We want our code to be comprehensible, because that is the first step on the way to
maintainability. The first step to comprehensibility is to break computational tasks into
meaningful chunks (represented as functions and classes) and name those. Such functions
then provide the basic vocabulary of computation, just as the types (built-in and userdefined) provide the basic vocabulary of data. The C++ standard algorithms (e.g., find,
sort, and iota) provide a good start (Chapter 12). Next, we can compose functions
representing common or specialized tasks into larger computations.
The number of errors in code correlates strongly with the amount of code and the
complexity of the code. Both problems can be addressed by using more and shorter
functions. Using a function to do a specific task often saves us from writing a specific
piece of code in the middle of other code; making it a function forces us to name the
activity and document its dependencies.
If two functions are defined with the same name, but with different argument types, the
compiler will choose the most appropriate function to invoke for each call. For example:
void print(int);
void print(double);
void print(string);
void user()

// takes an integer argument
// takes a floating-point argument
// takes a string argument


{



double s3 = sqrt("three");

// error: sqrt() requires an argument of type double

Không nên đánh giá thấp giá trị của việc kiểm tra thời gian biên dịch và chuyển đổi kiểu.
Một khai báo hàm có thể chứa tên đối số. Đây có thể là một trợ giúp cho người đọc
chương trình, nhưng trừ khi phần khai báo cũng là một định nghĩa hàm, trình biên dịch chỉ
cần bỏ qua các tên như vậy. Ví dụ:
double sqrt(double d);
double square(double);

// return the square root of d
// return the square of the argument

Kiểu của một hàm bao gồm kiểu trả về của nó và chuỗi các kiểu đối số của nó. Ví dụ:
double get(const vector<double>& vec, int index); // type: double(const vector<double>&
, int)

Một hàm có thể là thành viên của một lớp (§2.3, §4.2.1). Đối với một hàm thành viên như
vậy, tên của lớp của nó cũng là một phần của kiểu hàm. Ví dụ:
char& String::operator[ ](int index);

// type: char& String::(int)

Chúng ta muốn mã của mình phải dễ hiểu, bởi vì đó là bước đầu tiên trên con đường đạt
được khả năng bảo trì. Bước đầu tiên để dễ hiểu là chia các nhiệm vụ tính tốn thành các
phần có ý nghĩa (được biểu diễn dưới dạng các hàm và lớp) và đặt tên cho chúng. Các chức
năng như vậy sau đó cung cấp vốn từ vựng cơ bản về tính tốn, cũng như các kiểu (cài sẵn
và do người dùng định nghĩa) cung cấp từ vựng cơ bản về dữ liệu. Các thuật tốn tiêu chuẩn
C++ (ví dụ: find, sort và iota) cung cấp một khởi đầu tốt (Chương 12). Tiếp theo, chúng ta

có thể soạn các hàm đại diện cho các tác vụ thơng thường hoặc chun biệt thành các tính
tốn lớn hơn.
Số lượng lỗi trong mã tương quan chặt chẽ với số lượng mã và độ phức tạp của mã. Cả
hai vấn đề đều có thể được giải quyết bằng cách sử dụng nhiều hàm hơn và ngắn hơn. Sử
dụng một hàm để thực hiện một nhiệm vụ cụ thể thường giúp chúng ta không phải viết một
đoạn mã cụ thể ở giữa đoạn mã khác; khiến nó trở thành một hàm buộc chúng ta phải đặt
tên cho hoạt động và ghi lại các phụ thuộc của nó.
Nếu hai hàm được định nghĩa với cùng một tên, nhưng với các kiểu đối số khác nhau,
trình biên dịch sẽ chọn hàm thích hợp nhất để gọi cho mỗi lần gọi. Ví dụ:
void print(int);
void print(double);
void print(string);

// takes an integer argument
// takes a floating-point argument
// takes a string argument


void user()
{

print(42);
print(9.65);
print("Barcelona");

// calls print(int)
// calls print(double)
// calls print(string)

}


If two alternative functions could be called, but neither is better than the other, the call is
deemed ambiguous and the compiler gives an error. For example:
void print(int,double);
void print(double,int);
void user2()
{
print(0,0);
}

// error : ambiguous

Defining multiple functions with the same name is known as function overloading and is
one of the essential parts of generic programming (§7.2). When a function is overloaded,
each function of the same name should implement the same semantics. The print()
functions are an example of this; each print() prints its argument.

1.4 Types, Variables, and Arithmetic
Every name and every expression has a type that determines the operations that may be
performed on it. For example, the declaration
int inch;

specifies that inch is of type int; that is, inch is an integer variable.
A declaration is a statement that introduces an entity into the program. It specifies a type
for the entity:
● A type defines a set of possible values and a set of operations (for an
object).
● An object is some memory that holds a value of some type.
● A value is a set of bits interpreted according to a type.



● A variable is a named object.
C++ offers a small zoo of fundamental types, but since I’m not a zoologist, I will not list
them all. You can find them all in



×