Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
 1
Lab Exercises: LAB 2 
(Vectors,  introduction to pointers and virtual functions) 
 
General guidance: 
 
1. You will need to log on to your Linux environment for this lab. 
2. Use a text editor of your preference to edit the code. For today's lab you will not need anything more 
complicated. 
3. For quick on-line reference use (a book is preferable): http://www.cppreference.com/ 
4. Use the g++ compiler at the command line: For example g++ ex1.cc -Wall -o ex1 will 
compile the source file ex1.cc and will generate the executable code in the program file ex1. 
5. You can run a program from the directory where you compiled it by typing (for the above example): 
./ex1 
6. Use the mkdir command to create a directory structure like, e.g. your_home/CIP/labs/lab2. If 
unsure ask for help. Then cd to lab2. 
 
NOTE: It does not matter what file extension you use for your source files, .cc, .cpp – It is a 
matter of stylistic preference. 
 
 
Exercise 1. 
 
Vectors 
#include  
 
Vectors in C++ are powerful and easy to use. They combine the best features of arrays and vectors in 
Java. 
    vector vecInt(5);  // vector of 5 integers 
    vector vecStr;  // empty vector of strings 
 
Unlike Java, there is no run-time control for legal indexes, and therefore accessing an illegal index can 
cause very serious errors.  
Vectors can be accessed just like arrays: 
    vecInt[1] = x; 
    vecInt[2] = vecInt[1] + 3; 
 
You can add more elements with the push_back method (single element to the end of the vector): 
    strVec.push_back(s); 
 
Similarly, you can remove the last elemet from the vector with: 
  strVec.pop_back(s); 
 
The current length of strVec is strVec.size()  
 
-    Create a bank account class. Your class should contain private fields for the customer's name and a 
balance, one or more constructors, extractor methods to access the name and balance, and methods to 
deposit and withdraw an amount. 
 
-    Write a simple main function that creates a few of these objects and tests them. 
 
-    Move some of the methods out of the class, and get the result to compile. 
 
-    Define a bank class, containing a vector of bank accounts, with methods to add a new account and to 
print all the accounts. 
 
 2
-    Have a look at the other functions available for Vector in C++ (e.g. from the suggested on-line 
reference), and incorporate some in your code. 
 
-    Add a method to deposit a specified amount into the account of a named customer, and another to 
similarly withdraw. Use your print method to test them. 
 
-    Add a method to add a specified amount of interest (e.g. 1.75 meaning 1.75%) to each account in the 
bank. Test it with your print method. 
 
Exercise 2. 
 
Introduction to pointers 
 
A pointer is a variable that holds a memory address. 
 
So, a pointer to an integer myInt is the memory address of myInt. 
 
To declare a pointer to, e.g., an integer, we place the star operator * between the data type and the variable 
name. For example: 
int *myIntPointer; 
 
The & operator now places into myIntPointer the memory address of the variable count 
int count; 
myIntPointer = &count; 
 
The * operator, apart from declaring a pointer, also dereferences a pointer, i.e., it gets the actual value 
stored in the memory address that the pointer points to. 
 
q = *myIntPointer; 
 
A. What do you think is going to be the output of the following program? Type the following code in a 
source file (with the appropriate include statement), compile it and run it. Does the output match your 
expectations? 
 
int main() { 
    int myInt = 1000; 
    int *myIntPointer = &myInt; 
       // declare a pointer to an integer 
                              // and make it point to myInt 
 
    cout << myInteger << ‘ ’ << myIntPointer;  
} 
 
 
B. What about the following code? What will be the output? Can you figure out what is happening? Add 
code to print out the memory addresses of myInt and mySecondInt to get a better understanding 
of what is happening. 
 
int main() { 
 
    int myInt = 1000; 
    int *myIntPointer = &myInt; 
 
    // declare another integer whose value is the same as the integer 
    // at memory address  
    int mySecondInt = *myIntPointer; 
 
    cout <<  myInt <<’ ‘; 
 3
 
    // dereference the pointer and add 5 to the integer it points to 
    *myIntPointer += 5; 
 
    cout << myInt << ‘ ’; 
 
 cout << mySecondInt; 
} 
 
More on pointers at the lecture on Thursday, and at next week’s lab. 
 
Exercise 3. 
Virtual Functions 
 
Consider the following piece of code in Java: 
 
public void aMethod() { 
   Object obj = new String("Hello World"); 
   String output = obj.toString(); // calls String.toString(), 
                                   // not Object.toString() 
} 
 
The method toString() is defined in class Object and overridden in class String. In our example, 
Java knows that obj is really of type String, so at run-time it calls the String.toString() 
method. (This is polymorphism at work.) It can resolve which method to call at run-time since in Java, all 
methods are virtual. In a virtual method, the compiler and loader (or VM) make sure that the correct 
version of the method is called for each particular object. 
 
In C++ you have to explicitly declare a function as virtual, and override it in a subclass. C++ determines 
which version of the function to cal at run-time.If you don’t explicitly declare it, the compiler may not call 
the correct version of the function – but the program will still compile.  
 
Although this may appear similar to overloading, it is not: The main difference is that the prototype for a 
redefined virtual function must match exactly that for the prototype of eth function in the base (parent) 
class. 
 
 
A. Consider this example: 
 
#include  
using namespace std; 
 
class base { 
public: 
 virtual void vfunc() { 
  cout << “This is base’s vfunc().\n”; 
 } 
}; 
 
class derived1 : public base { 
public: 
 void vfunc() { 
  cout << “This is derived1’s vfunc().\n”; 
 } 
}; 
 
int main() 
{ 
 base *p, b; 
 4
 derived1 d1; 
 
 p = &b; 
 p->vfunc(); 
 
 p = &d1; 
 p->vfunc(); 
 
 return 0; 
} 
 
- Can you figure out what happens in this example? What will the output in main be? 
- Based on the short introduction to pointers previously, can you follow what happens in main with the 
* and & operators? 
- What does p->vfunc() actually do? Why do we need -> and do not use the normal notation 
p.vfunc()? Can you think of an alternative notation for -> ? 
 
B.  
Now make a copy in this week’s directory (lab3) of the files you used for exercise 6 from last week. We 
will need to extend it a bit. 
 
- Add a virtual function in the base (parent) class Building, called build that prints “I am building 
a Building”. 
- Add a function build in House that prints “I am building a House”. 
- Add a new subclass (derived class) of Building, called Igloo. Igloo will have two more 
variables: string name, int iceBlocks. Add a function build in Igloo that prints “I am 
building an Igloo”. 
- Now following the example in Part A, add a main function that creates a pointer to the base class 
Building, and that also creates instances of at least one House and one Igloo. Test the virtual 
function build by calling it with objects of different classes, as in the example. 
- Now let us complicate things a little bit more: Create a derived class (subclass) of House, let’s call 
the new class farmHouse. The new class will have one more variable, double farmLandArea. 
- Now let’s add a function build in farmHouse that prints “I am building a Farm House”. 
- Do the appropriate modifications in main to test the new build function. What do you see 
happening? What can you say about the inheritance of the virtual property in functions?