Transfer from: http://www.prglab.com/blog/p/48
Translation: Aqua prglab.com
Note: Many programmers, including myself is to learn the Java, and knowledge, the C + +, in fact C + + and Java there are many similarities and exchange between, there is considerable Java knowledge can be related to conversion to a C + + concepts to help us quickly get started . This article describes the contents of the on from Java to C + + transformation helpful, so translation recommended to have the same friend in need. Translation joined my understanding, is not entirely full copy. Are unknown or objections, please refer to the original, or a message to discuss. Again, recommended to read original data.
Learn how to transfer from one programming language to another programming language is today's programmers must face the reality, better, C + + and Java share many common characteristics, so from Java to C + + on much easier. C + + much more complex than Java, the paper did not intend to cover all the C + + functions. But if you can master all the knowledge points in this article, but also sufficiently effective use of C + +,.
Here we speak only Java and C + +, different. Such as flow control (if, while, for) those in C + + and Java, the content here is not exactly the same spoke.
This article is based on the ANSI C + + standard, some of the old C + + compilers may not support some of the important features mentioned here. To use these compilers, you need more to learn C + +, inherited from the C part. Those who are beyond the scope of this article, and not introduced.
1. Data types and variables
C + +, variable types and Java are very similar. The same as Java, C + + with int and double types. However, these figures range type is dependent on the machine. For example, in 16-bit systems, such as running DOS or Windows 3.x for PC machines, int is the double-byte (2-byte), the range of 4-byte than Java, the int to be much smaller. In these machines, if int is not enough, you need to use a long integer long.
C + + are short and unsigned types to more efficient storage figures. (I think the so-called effective space utilization is higher.) It is best to avoid using these types except the effectiveness of space utilization on your system is really very important.
In C + +, use bool Boolean that unlike in Java using boolean.
C + +, use string, said string type. String it with Java in a very similar type, but still want to differences between each of the following:
1. C + + code strings stored in ASCII characters, Unicode characters instead of the standard code
2. C + + strings can be modified, while Java can not modify the contents of a string of (immutable).
3. Take sub-string operation in C + +, called the substr, this command s.substr (i, n) obtained from the string s starting from position i of length n substrings.
4. In C + +, you can only object to a string with other strings in series (concatenate), but not with any object can be connected in series.
5. C + + can be used directly ties operator ==,! =, <, <=,>,> = To carry out a string comparison, which is behind the four operators compare in alphabetical order. Than Java, use the function equals and compareTo to compare the convenience of many.
2. Variables and constants
In C + + in the definition of local variables look the same with Java, for example:
int n = 5;
In fact, this is C + + and Java is an important difference. C + + compiler does not initialize local variables tested, so in C + +, very easy to forget to initialize a variable, in which case, the value of the variable percentage of the variable memory area exists just the current random value. This is obviously very prone to error, place.
As with Java, C + + in the class can have data fields and static variables. The difference is, C + + variables can function even outside the class definition, these so-called global variables can be any function in the program to be accessed, and thus difficult to be well managed. The C + +, should avoid using global variables.
In C + +, the constants can be defined anywhere (remember Java, constants must be the class static data static data). C + + using the const keyword to define constants, but Java is final. For example:
const int DAYS_PER_YEAR = 365;
C + +, Java definition of the class is different, here is an example: a C + + version of the Point class:
class Point / * C + + * /
Point (double xval, double yval);
void move (double dx, double dy);
double getX () const;
double getY () const;
Some important difference here is:
1. C + + class definition is divided into public and private parts, beginning with keywords public and private. In Java, each element must be marked public or private.
2. C + + in the class definition only contains the function declaration, the real implementation are listed separately.
3. Access function (accessor methods) marked with the keyword const, that this function does not change the value of the object element.
4. Class definition has a semicolon at the end of
Implementation class function with the following definition of the class. Because the function is defined outside the class, so every name in front of a function name as a prefix to add class and use the double-colon operator:: to split the class name and the name of the function. Does not change the hidden parameter values (ie the current value of the object) of the access function is marked with const. Follows the above class definition is a function of implementation:
Point:: Point () (x = 0; y = 0;)
void Point:: move (double dx, double dy)
x = x + dx;
y = y + dy;
double Point:: getX () const
Java and C + + The main difference is the use of object variable. In C + +, object variables are stored in the value of the real object, not object reference ( reference ). Note that in C + + in the structure when an object is not to use keyword new, and only the variable name followed directly give the parameters of the constructor can be, for example:
Point p (1, 2); / * construct an object p * /
If you do not with the parameters of the assignment, use the default constructor, for example:
Time now; / * default constructor Time:: Time () * /
This is very different with Java. In Java, this command only generates an uninitialized reference, while in C + +, it generates an actual object.
When an object is assigned to another object variable, the actual value will be copied. In Java, copying an object variable is only set up one other point to an object reference. Copy a C + + objects as in Java, as this function is called clone, copy the value to modify the original object will not change the value. For example:
Point q = p; / * copy p to q * /
q.move (1, 1); / * move q and p fixed, that is, change the value of q, while p constant * /
In most cases, C + + in this object's properties directly on the value of operation is very easy to use, but also sometimes less than satisfactory:
1. When you need a function to modify an object's value, you must remember to use call by reference call by reference (see the following function in part)
2. Two object variables can not point to the same object entity. If you want to achieve in the C + +, this effect, you must use the pointer to pointer (see the following pointer part)
3. An object variable can only store a particular type of value, if you want to use a variable to store objects of different subclasses value (polymorphism ploymorphism), you need to use pointers.
4. If you want to use in C + +, or point to a variable to null or point to an actual object, you need to use the pointer
In Java, every function must be either the object function (instance method), or a static function (static function), or class functions. C + + also supports object functions and static functions (class functions), but also allows the definition of C + + does not belong to any class of functions that are called global functions (global functions).
In particular, every C + + programs are from a global function called main started:
int main ()
There is another form of the main functions can be used to capture command-line arguments, similar to Java's main function, but it requires an array of formats and on the C string knowledge, not described here.
In accordance with usual and customary procedures for implementation, if successful, main function returns 0, otherwise non-zero integer.
As with Java, a function parameter is passed by value (passed by value). In Java, the function can be modified in any case is the value of the object. However, in C + +, because the object is directly stored in the actual value, rather than the point value of the reference, that is passed into the function is a copy of the actual value, and therefore can not modify the original value of the object.
Therefore, C + +, there are two parameters passing mechanism, the same as with Java call by value (call by value), and the call by address (call by reference). When a parameter is passed by reference, the function can modify its original value. Call by reference parameters have an address number in front & back with the parameter type, for example:
void raiseSalary (Employee & e, double by)
The following is a typical function using call by reference, can not be achieved in Java, such functionality.
void swap (int & a, int & b)
(Int temp = a;
a = b;
b = temp;
If you use the swap (x, y) to call this function, the reference parameters a and b point to the actual parameters of the original x and y position, not a copy of their values, so this function can realize the real value of the exchange of these two parameters .
In C + +, whenever the need to achieve changes the value of the original parameters you can use call by address call by reference.
6. Vector Vector
C + +, Java in the vector structure combining the advantages of both arrays and vectors. A C + + vector can easily be accessed, its capacity and can grow dynamically. If T is any type, then the vector <T> is an element for the T type of dynamic arrays. The following statement
vector <int> a;
Create an initial empty vector. The statement
vector <int> a (100);
Generates an initial vector of 100 elements. You can use the push_back function to add elements:
Call a.pop_back () removed from a last element (the element after operation is the deletion from a), using the function size can be present in a number of elements.
You can also familiar  operator to access the vector elements, such as:
for (i = 0; i <a.size (); i + +) (
sum = sum + a [i];
With Java, as the array index must be 0 and a.size () - 1 values between. But the difference is that with Java, C + + runtime the index number is not the legality of testing. Illegal attempt to access the index position can cause very serious error.
Like all other C + + objects, vector is the value. If you assign a vector to another vector variable, all the elements will be copied in the past.
vector <int> b = a; / * all the elements have been copied * /
Contrast the situation in Java, in Java, an array variable is a pointer to an array reference. Copy of this variable produced only one other point to the same array reference, and will not copy the value of each element.
For this reason, if a C + + function to modify the vector of values to achieve, you must use the reference parameters:
void sort (vector <int> & a)
7. Input and output
In C + +, the standard input and output streams cin and cout said the object. We use the <<operator to write output, for example:
cout <<"Hello, World!";
The output of the content can also be attached, for example:
cout <<"The answer is" <<x <<"\ n";
We use the>> operator to read a number or word, such as:
cout <<"Please enter x:";
cout <<"Please enter your first name:";
Function getline can read the entire line of input, such as:
getline (cin, inputLine);
If you reach the end of the input, or a number can not be read correctly, the stream object will be set to failed state, we can use the function fail to test this state, for example:
if (cin.fail ()) cout <<"Bad input";
Once a flow state is set to failed, we reset its status is very difficult, so if your program needs to handle error input, you should use the function getline and then manually processed by the input data.
8. Pointer pointer
We already know the C + +, object variables are stored directly in the value of the object. This is different from Java, in Java, an object variable is stored in an address, the address points to the object value of the actual storage place. Sometimes also in C + + need to implement this arrangement, which uses a pointer to pointer. In C + +, a pointer pointing to an object variable is called. If T is a data type, then T * is the point of this data type pointer. Here focuses on C + + and Java differences, to learn more about C + +, the use of pointers, please refer to website another article " C + + in the Reference and pointer (Pointer) the use of contrast . "
Like Java, like a pointer variable can be initialized to null value NULL, the value of another pointer variable, or a new object called new generation:
Employee * p = NULL;
Employee * q = new Employee ("Hacker, Harry", 35000);
Employee * r = q;
In fact in C + +, a fourth possibility is that the pointer can be initialized to the address of another object, which need to use the address operator &:
Employee boss ("Morris, Melinda", 83000);
Employee * s = &boss;
This is actually not a good idea. Insurance, or should the practice of direct pointer to the new object using the new generation.
So far, C + + pointer looks very much like Java's object variable. However, there is a very important grammatical differences. We must use the asterisk operator * to access the pointer to the object. If p is a pointer to a pointer Employee object, then * p only represent this object:
Employee * p =...;
Employee boss = * p;
When we need to perform a function or object of a data access object fields, they need to use * p:
(* P). SetSalary (91000);
* P out of the brackets is necessary because. Operator than the * operator has higher priority. C designers think of this formulation is difficult to see, so they provide another alternative formulation, using the -> operator to achieve * and. A combination of operator functions. Expression
p-> setSalary (91000);
Can call a function of the object * p setSalary. You can easily remember. Operator is used in the object, -> pointer operator is used.
If you do not initialize a pointer, or null if a NULL pointer or points to an object no longer exists, then it is used above * or -> operator would be wrong. Unfortunately, C + + runtime system does not check this error. If you Fan of this error, your program may act strange or crash.
In Java, these errors will not occur. All of the reference must be initialized, all the objects as long as the reference point it still will not be removed from memory, so you do not have a point to the object has been deleted reference. Java's runtime system checks whether the reference is empty, and null pointer thrown in the face of a null pointer exception (exception).
C + + and Java there is a significant difference is that Java has garbage collection feature that can automatically recover the abandoned object. In C + +, you need to manage their own memory allocation programmer recovery.
C + +, when the object variable goes out of scope can be automatically recovered. However, the object generated using the new operator must manually delete to delete, such as:
Employee * p = new Employee ("Hacker, Harry", 38000);
delete p; / * do not need this object * /
If you forget to delete an object, then your program may eventually run out of all the memory. This is what we often say that the memory leak (memory leak). More importantly, if you if you delete an object, and then continue to use it, you might overwrite the data does not belong to you. If you happen to cover the memory for processing the data recovery field, then the memory allocation mechanism may be caused by abnormal functioning of a more serious errors, and difficult to diagnose and repair. Therefore, the best C + +, minimize the use of pointers.
C + + and Java, the basic syntax of inheritance is very similar. In C + +, use: public instead of Java in inheritance extends to that. (C + + also supports the concept of private inheritance, but not very useful.)
By default, C + + in the function is not dynamic binding. If you need a function to achieve dynamic binding, need to use the virtual states that it is virtual function, for example:
class Manager: public Employee
Manager (string name, double salary, string dept);
virtual void print () const;
As with Java, the constructor calls the parent class constructor has a special syntax. Java use the keyword super. C + +, need to subclass the parent class constructor calls the constructor in vitro function. Here is an example:
Manager:: Manager (string name, double salary, string dept)
: Employee (name, salary) / * call the parent class constructor * /
(Department = dept;
Java, in the sub-class of functions in the function call when the parent class using the keyword super. In C + +, is to use the name of the parent class with operator:: that, for example:
void Manager:: print () const
(Employee:: print (); / * call the parent function * /
cout <<department <<"\ n";
A C + + object variable can only store a specific type of object value. To implement the C + + polymorphism (polymorphism), you must use a pointer. T * pointer can point to a type T or T, the object of any subclass, such as:
Employee * e = new Manager ("Morris, Melinda", 83000, "Finance");
You can subclass the parent class and the different objects are mixed to collect a pointer to the vector element, then call the dynamic binding of function, as follows:
vector <Employee*> staff;
for (i = 0; i <staff.size (); i + +)
staff [i] -> print ();