(103)
(1)
(76)
(26)
分类: java
2015-01-06 13:17:09
this appendix explains how to transfer your java programming skills to a substantial subset of c . this is necessary for students who take their first programming course in java and the second course in c . naturally, it would be easiest if the second course were also offered in java, but learning to move from one language to another is a fact of life for today's software professionals. fortunately, c has many features in common with java, and it is easy for a java programmer to gain a working knowledge of c . nevertheless, c is a much more complex language than java. this appendix does not attempt to cover all features of c . but if you master all of the constructs described in this appendix, you will be able to use c effectively.
we only cover the differences between java and c . in particular, control flow (if, while, for) is essentially identical in c and java, and it is not covered here.
this appendix describes ansi c . some older c compilers lack essential features described here. to use those compilers, you will need to learn more about the parts of c that were inherited from c. that is beyond the scope of this discussion.
the data types in c are similar to those in java. like java, c has int and double types. however, the range of the numeric types such as int is machine-dependent. on 16-bit systems such as pcs running dos or windows 3.x, int are 2-byte quantities with a much more limited range than the 4-byte java int type. on those machines, you need to switch to long whenever the int range is not sufficient.
c has short and unsigned types that can store numbers more efficiently. it is best to avoid these types unless the added efficiency is crucial.
the boolean type is called bool in c .
the c string type is called string. it is quite similar to the java string type. however, pay attention to these differences:
1. c strings store ascii characters, not unicode characters
2. c strings can be modified, whereas java strings are immutable.
3. the substring operation in c is called substr. the command s.substr(i, n) extracts a substring of length n starting at position i.
4. you can only concatenate strings with other strings, not with arbitrary objects.
5. to compare strings, use the relational operators == != < <= > >=. the last four operators perform lexicographic comparison. this is actually more convenient than the use of equals and compareto in java.
in c , local variables are defined just as in java.
int n = 5;
there is, however, a major difference between c and java. the c compiler does not check whether all local variables are initalized before they are read. it is quite easy to forget initializing a variable in c . the value of the variable is then the random bit pattern that happened to be in the memory location that the local variable occupies. this is clearly a fertile source of programming errors.
as in java, classes can have data fields and static variables. furthermore, variables can be declared outside functions and classes. these so-called global variables can be accessed from any function in a program. that makes them difficult to manage. c programs should avoid global variables.
in c , constants can be declared anywhere. (recall that in java, they had to be static data of a class.) c uses the const keyword instead of final.
const int days_per_year = 365;
the definition of classes in c is somewhat different than in java. here is an example: a c version of the point class:
class point /* c */
{
public:
point();
point(double xval, double yval);
void move(double dx, double dy);
double getx() const;
double gety() const;
private:
double x;
double y;
};
there are several essential differences.
1. in c , there are public and private sections, started by the keywords public and private. in java, each individual item must be tagged with public or private.
2. the class definition only contains the declarations of the methods. the actual implementations are listed separately.
3. accessor methods are tagged with the keyword const
4. there is a semicolon at the end of the class
the implementation of methods follows the class definition. because the methods are defined outside the classes, each method name is prefixed by the class name. the :: operator separates class and method name. accessor methods that do not modify the implicit parameter are tagged as const.
point::point() { x = 0; y = 0; }
void point::move(double dx, double dy)
{ x = x dx;
y = y dy;
}
double point::getx() const
{ return x;
}
the major difference between java and c is the behavior of object variables. in c , object variables hold values, not object references. note that the new operator is never used when constructing objects in c . you simply supply the construction parameters after the variable name.
point p(1, 2); /* construct p */
if you do not supply construction parameters, then the object is constructed with the default constructor.
time now; /* construct now with time::time() */
this is very different from java. in java, this command would merely create an uninitialized reference. in c , it constructs an actual object.
when one object is assigned to another, a copy of the actual values is made. in java, copying an object variable merely establishes a second reference to the object. copying a c object is just like calling clone in java. modifying the copy does not change the original.
point q = p; /* copies p into q */
q.move(1, 1); /* moves q but not p */
in most cases, the fact that objects behave like values is very convenient. there are, however, a number of situations where this behavior is undesirable.
1. when modifying an object in a function, you must remember to use call by reference (see below)
2. two object variables cannot jointly access one object. if you need this effect in c , then you need to use pointers (see below)
3. an object variable can only hold values of a particular type. if you want a variable to hold objects from different subclasses, you need to use pointers
4. if you want a variable point to either null or to an actual object, then you need to use pointers in c
in java, every function must be an instance method or a static function of a class. c supports instance methods and static functions of classes, but it also permits functions that are not a part of any class. such functions are called global functions.
in particular, every c function starts with the global function main.
int main()
{ . . .
}
there is a second version of main that you can use to capture command-line arguments, but it requires knowledge of c-style arrays and strings, and we will not cover it here.
by convention, the return value of main is zero if the program completed succesfully, a non-zero integer otherwise.
as in java, function arguments are passed by value. in java, functions were nevertheless able to modify objects. however, since c object values are not references to actual objects, a function receives a copy of the actual argument and hence can never modify the original.
therefore, c has two parameter passing mechanisms, call by value (as in java) and call by reference. when a parameter is passed by reference, the function can modify the original. call by reference is indcated by an & behind the parameter type.
void raisesalary(employee& e, double by)
{ . . .
}
here is a typical function that takes advantage of call by reference. note that it would be impossible to write such a function in java.
void swap(int& a, int& b)
{ int temp = a;
a = b;
b = temp;
}
if this function is called as swap(x, y), then the reference parameters a and b refer to the locations of the arguments x and y, not the values of these arguments. hence the function can actually swap the contents of these variables.
in c , you always use call by reference when a function needs to modify a parameter.
the c vector construct combines the best features of arrays and
vectors in java. a c vector has convenient element access, and it can
grow dynamically. if t is any type, then vector
vector
makes an initially empty vector. the command
vector
makes a vector that has initially 100 elements. you can add more elements with the push_back method:
a.push_back(n);
the call a.pop_back() removes the last element from a. use the size method to find the current number of elements in a.
you access the elements with the familiar [] operator.
for (i = 0; i < a.size(); i )
sum = sum a[i];
as in java, array indexes must be between 0 and a.size() - 1. however, unlike java, there is no runtime check for legal array indexes. accessing an illegal index can cause very serious errors.
just like all other c objects, vectors are values. if you assign one vector to another, all elements are copied.
vector
contrast that with the situation in java. in java, an array variable is a reference to the array. making a copy of the variable just yields a second reference to the same array.
for that reason, c functions that modify vectors must use reference parameters.
void sort(vector
{ . . .
}
in c , the standard input and output stream are represented by the cin and cout objects. you use the << operator to write output.
cout << "hello, world!";
you can print multiple items as well.
cout << "the answer is " << x << "\n";
to read a number or a word from input, use the >> operator.
double x;
cout << "please enter x: ";
cin >> x;
string fname;
cout << "please enter your first name: ";
cin >> fname;
the getline method reads an entire line of input.
string inputline;
getline(cin, inputline);
if the end of input has been reached, or if a number could not be read correctly, the stream is set to a failed state. you can test for that with the fail method.
int n;
cin >> n;
if (cin.fail()) cout << "bad input";
once the stream state has failed, you cannot easily reset it. if your program needs to handle bad input, you should use getline and then manually process the input.
in c , object variables hold object values. this is different from java, where an object variable only is a reference to an object value that is stored elsewhere. there are circumstances where the same arrangement is required in c . in c , a variable that can refer to an object is called a pointer. if t is any type, then t* is a pointer to an object of type t.
just as in java, a pointer variable can be initialized with null, with another pointer variable, or with a call to new.
employee* p = null;
employee* q = new employee("hacker, harry", 35000);
employee* r = q;
actually, there is a fourth possibility. pointers can be initialized with the address of another object, by using the & operator.
employee boss("morris, melinda", 83000);
employee* s = &boss;
this is usually not a good idea. as a rule of thumb, c pointers should only refer to objects allocated wth new.
so far, c pointers look very much like java object variables. there is, however, an essential syntactical difference. you must apply the * operator to access the object to which a pointer points. if p is a pointer to an employee object, then *p refers to that object.
employee* p = . . .;
employee boss = *p;
you also need to refer to *p when you want to execute a method or access a data field.
(*p).setsalary(91000);
the parentheses are necessary because the . operator has a higher precedence than the * operator. the designers of c found this sufficiently ugly that they provided an alternate -> operator to combine the * and . operators. the expression
p->setsalary(91000);
invokes the setsalary method on the object *p. you can simply remember to use the . operator for objects, the -> operator for pointers.
if you do not initialize a pointer, or if the pointer is null or refers to an object that no longer exists, then it is an error to apply the * or -> operator. unfortunately, the c runtime system does not check against these errors. if you make such a mistake, your program can die a horrible death or act flaky.
in java, these errors are not possible. you cannot have an uninitialized reference. all objects are kept alive as long as there is a reference to it. hence you cannot have a reference to a deleted object. the runtime system checks for null references and throws a null pointer exception if a null pointer is accessed.
there is another significant difference between c and java. java has a garbage collector that automatically reclaims all objects that are no longer needed. in c , it is the responsibility of the programmer to manage memory.
object variables are automatically reclaimed when they go out of scope. however, objects created with new must be reclaimed manually with the delete operator.
employee* p = new employee("hacker, harry", 38000);
. . .
delete p; /* no longer need this object */
if you forget to delete an object, then you can eventually exhaust all memory. this is called a memory leak. more importantly, if you delete an object and then continue to use it, you can overwrite data that no longer belongs to you. if you overwrite any of the data fields that are used to manage the recycled storage, the allocation mechanism can malfunction and cause subtle errors that are very difficult to diagnose and fix. for this reason, it is best if you minimize the use of pointers in c .
the basic syntax for inheritance is similar in c and java. in c , you use : public instead of extends to denote inheritance. (c also supports a concept called private inheritance, but it is not very useful.)
by default, functions are not dynamically bound in c . if you want which dynamic binding for a particular function, you must declare it as virtual.
class manager : public employee
{
public:
manager(string name, double salary, string dept);
virtualvoid print() const;
private:
string department;
};
as in java, there is special syntax for a constructor to invoke the constructor of the superclass. java uses the keyword super. in c , you must call the superclass constructor outside the body of the subclass constructor. here is an example.
manager::manager(string name, double salary, string dept)
: employee(name, salary) /* call superclass constructor */
{ department = dept;
}
java also uses the super keyword when a subclass method calls the superclass method. in c , you use the name of the superclass and the ::operator instead.
void manager::print() const
{ employee::print(); /* call superclass method */
cout << department << "\n";
}
a c object variable holds objects of a specific type. to exploit polymorphism in c , you need pointers. a t* pointer can point to objects of type t or any subclass.of t.
employee* e = new manager("morris, melinda", 83000, "finance");
you can collect multiple objects of a mixture of super- and subclasses in a vector of pointers, and then apply a dynamically bound function.
vector
. . .
for (i = 0; i < staff.size(); i )
staff[i]->print();
上一篇:
下一篇: