2011年12月28日 星期三

Introductory C++ Concepts - Default Arguments





Default Arguments

Default arguments is a shortcut that is not available in C. It allows function arguments to automatically be provided in the function call. Default arguments are commonly used when a function is called repeatedly using the same argument value(s)

Here's an example of a function, power(), that has a default argument. 

Example 2-4

1      // File:  ex2-4.cpp
2     
3      #include <iostream>
4      using namespace std;
5     
6      long power(int,int = 2);    // function prototype with default argument
7     
8      int main(void)
9      {
10          cout << power(5) << endl;        // use default argument
11          cout << power(2,10) << endl;     // don’t use default argument
12          cout << power(12345) << endl;     // use default argument
13     
14          return 0;
15      }
16     
17     
18      long power(int x, int y)
19      {
20          long num = 1;
21          for (int i = 1; i <= y; i++) num *= x;
22          return num;
23      }


*****  Sample Output  *****

25
1024
152399025


A function may possess several default arguments. Such as ...

void funk1 (int, double, int = 5, double = 3.14);

or

int funk2 (int = 1, int = 2, int = 3, int = 4);

Call's to funk1 could look like:

funk1(2,3.14,6,1.23)    // all arguments are supplied

or

funk1(2,3.14,6)            // the same as funk1(2,3.14,6,3.14)

or

funk1(2,3.14)            // the same as funk1(2,3.14,5,3.14)

Calls to funk2 could look like:

funk2(2,4,6,8)        // all arguments are supplied

or

funk2(2,4,6)        // the same as funk2(2,4,6,4)

or

funk2(2,4)            // the same as funk2(2,4,3,4)

or

funk2(2)            // the same as funk2(2,2,3,4)

or

funk2()            // all arguments are default

Notes
  • In a function argument list, mandatory arguments may never follow default arguments. For example, funk(int,int,int=2,int=5) is OK, but funk(int,int=3,int,int=6) is not OK. Default arguments must come at the end of the argument list.
  • Default arguments should be placed in the function prototype, not the function heading. This (strong) recommendation should be followed, even if your compiler permits the default argument in the function heading. The exception to this is the situation where the function is defined before it is called and, in this case, the prototype is not necessary.
  • Default arguments may not be repeated in both the function prototype and the heading of the function definition.

Default arguments 一定要在 argument list 的最後.
建議將 default arguments 放在 function prototype 下; 而不要再 function heading 下.

2011年12月27日 星期二

Introductory C++ Concepts - Reference Variables


Reference Variables

A reference variable is an alias for another variable. It is similar to a pointer in that it contains the address of a variable, but unlike a pointer, you do not need to perform any dereferencing yourself.

Reference variables must be initialized when they are declared, and they cannot be reassigned to refer to another variable.

Examples:

float pie = 3.14;
float& apple = pie;

Here's a little piece of code that shows how a reference works, but it's not very realistic, because it doesn't make sense to use a reference for another variable in the same function.

int x = 5;
int &z = x;    // z is another name for x

cout << x << endl; -> prints 5
cout << z << endl; -> prints 5

z = 9; // same as x = 9;

cout << x << endl; -> prints 9

cout << z << endl; -> prints 9

Important rule:  You must initialize references.

You may not declare a reference variable, like this:

int& ri;

Don't confuse it with the legal declaration of a pointer:

int* pi;

Guideline: References are used as function arguments (or parameters) or return types.

Example 2-1

This example compares two swap functions.  p_swap is written as the traditional swap function (that you would write in C).  r_swap is the equivalent version which uses references. Note the advantage of using references:
1. you don't have to pass the address of a variable
2. you don't have to dereference the variable inside the called function.

1      // File: ex2-1.cpp Reference Variables - swap functions
2     
3      #include <iostream>
4      using namespace std;
5     
6      // Function prototypes (required in C++)
7      void pointerSwap(int*, int*);
8      void referenceSwap(int& i1, int& i2);
9     
10      int main (void)
11      {
12          int x = 5;
13          int y = 7;
14     
15          cout << x << ' ' << y << endl;
16     
17          pointerSwap(&x,&y);
18     
19          cout << x << ' ' << y << endl;
20     
21          referenceSwap(x,y);
22     
23          cout << x << ' ' << y << endl;
24     
25          return 0;
26      }
27     
28      void pointerSwap(int *a, int *b)
29      {
30          int temp;
31          temp = *a;
32          *a = *b;
33          *b = temp;
34      }
35     
36      void referenceSwap(int &a, int &b)
37      {
38          int temp;
39          temp = a;
40          a = b;
41          b = temp;
42      } 


*****  Output  *****

5 7
7 5 - line 19 output
5 7 - line 23 output

Program Analysis

This is an extensive analysis of this simple program. Probably more than you want to read about, but it should give you some ideas about how you should analyze an example. Some of the really obvious details were skipped, but you still thought about them.

Line 7 This, of course, is a prototype for a function that takes two pointer to int arguments.  And, by the way what if the function prototype was written like?

void pointerSwap(int* n1, int* n2); or
void pointerSwap(int* a, int* b);     or
void pointerSwap(int *n1, int *n2); or
void pointerSwap(int* n1, int *n2); or
void pointerSwap(int *, int *);         or

It doesn't matter, they all mean the same thing. The * can be next to the int or next to a variable, or the variable doesn't even have to be there. This is just a style consideration.
Line 8 The int& function arguments mean that the arguments are references to int.
Line 17 Call the pointerSwap() function are pass in the addresses of two ints. Notice, that the was described (in the prototype discussion) as taking two pointer to int arguments, but when the function call is made here, you say that "the addresses of two ints" are passed in. You are, of course, familiar with this terminology from you C education.
Line 19 Here we see evidence that the pointer swap worked.
Line 21 In the call to the referenceSwap() function, note that the variable a just passed in (no addresses), just like a "pass by value". You know what that means, right?
Line 28 In the function definition heading, the function argument variable names do not have to match the variable names used in the function prototype. In the function argument, int *a, the * means that a is a pointer to an int, or the address of an int. 
Line 31 *a, here means dereference a,or take the value stored at the pointer address.
Line 32 Notice, here, that *a can be used as an "L value". In the line above, it is used as an "R value".
Line 36 The argument, int &a (or int& a), means that a is a refererce to an int, or a refers to an int that exists elsewhere. 
Line 39 Notice than when you use the reference, you don't need to defererence it. Herre's a secret – C++ accomplishes the reference utilization using pointers, but that none of your business!

It's often desirable to use a reference to a constant type to prevent changes to the referenced variable.

Example 2-2

This example shows function parameters passed as a reference and passed as a reference to const.

1      // File: ex2-2.cpp Reference Variables - function parameters
2     
3      #include <iostream>
4      using namespace std;
5     
6      void update_salary(double& sal)
7      {
8        sal *= 1.1;
9        return;
10      }
11     
12      void display_salary(const double &sal)
13      {
14        cout << sal << endl;
15        return;
16      }
17     
18     
19      int main (void)
20      {
21        double salary = 50000.;
22     
23        display_salary(salary);
24     
25        update_salary(salary);
26     
27        display_salary(salary);
28     
29        return 0;
30      } 


With reference variables, the & may be attached to either the variable type or the variable name as demonstrated in this example.

It is not common practice to "directly" use reference to an array.

Example 2-3

This example illustrates the use of references as function parameters in an example that is a little more sophisticated. The purpose of the example is determine won, lost and tied statistics for some teams. The example is a little shallow, but it does make use of references to structs. Before you read the example, take a look at the sample program run at the end, so you get the gist of what it's trying to accomplish.

1      // File: ex2-3.cpp Reference Variables - function parameters
2     
3      #include <iostream>
4      #include <cstring>
5      using namespace std;
6     
7      const int     NumTeams = 5;    // better than #define NumTeams 5
8      const int     NumScores = 11;
9     
10      // a team struct contains a team name and its W-L-T totals
11      struct team {
12        char        name[10];
13        unsigned    won;
14        unsigned    lost;
15        unsigned    tied;
16      };
17     
18      // the league struct contains an array of team structs
19      struct league {
20        team        teams[NumTeams];
21      };
22     
23      // this struct hold 2 team names and their points scored in a game
24      struct score {
25        char      teamname[2][10];
26        unsigned    points[2];
27      };
28     
29      // function prototypes
30      void     initializeLeague(league& L);
31      void     enterScores(score* S);
32      int    getTeamNumFromName(league& L, const char* Name);
33      void    updateWonLostTied(league& L, score* S);
34      void    printLeagueStats(league& L);
35     
36      int main (void) {
37        league    Birds;
38        score     Scores[NumScores];
39     
40        initializeLeague(Birds);
41        enterScores(Scores);
42        updateWonLostTied(Birds,Scores);
43        printLeagueStats(Birds);
44     
45        return 0;
46      }
47     
48      // Assign team names and zero out won, lost, tied
49      void initializeLeague(league& L) {
50        for (int i = 0; i < NumTeams; i++)
51        {
52          cout << "Enter team name => ";
53          cin >> L.teams[i].name;
54          L.teams[i].won = 0;
55          L.teams[i].lost = 0;
56          L.teams[i].tied = 0;
57        }
58        cout << endl << NumTeams << " teams initialized\n\n";
59      }
60     
61      void enterScores(score* S) {
62        cout << "Enter " << NumScores << " scores:\n";
63        for (int i = 0; i < NumScores; i++)
64        {
65          cout << "<team #1> <score #1> <team #2> <score #2> => ";
66          cin >> S[i].teamname[0] >> S[i].points[0]
67              >> S[i].teamname[1] >> S[i].points[1];
68        }
69        cout << endl << NumScores << " scores entered\n\n";
70      }
71     
72      // getTeamNumFromName() returns the index of the teams array
73      // (in the league struct) in which Name matchs the value
74      // of the league.teams[i].name.  If no match is found, the
75      // function return -1
76      int getTeamNumFromName(league& L, const char* Name) {
77        for (int i = 0; i < NumTeams; i++)
78        {
79          if (strcmp(L.teams[i].name,Name) == 0) return i;
80        }
81        cerr << "Error: unable to find team: " << Name << endl;
82        return -1;        // team name not found
83      }
84     
85      void updateWonLostTied(league& L, score* S) {
86        int        i,team0,team1;
87     
88      for (i = 0; i < NumScores; i++) {
89          team0 = getTeamNumFromName(L,S[i].teamname[0]);
90          team1 = getTeamNumFromName(L,S[i].teamname[1]);
91     
92      // if team name is bad, don't use the score
93          if (team0 == -1 || team1 == -1) continue;
94     
95          if (S[i].points[0] > S[i].points[1]) {    // team0 won
96            L.teams[team0].won++;
97            L.teams[team1].lost++;
98          }
99          if (S[i].points[0] < S[i].points[1]) {    // team1 won
100            L.teams[team1].won++;
101            L.teams[team0].lost++;
102          }
103          if (S[i].points[0] == S[i].points[1]) {    // tie game
104            L.teams[team0].tied++;
105            L.teams[team1].tied++;
106          }
107        }
108      }
109     
110      void    printLeagueStats(league& L) {
111        int    i;
112        cout << "\nName\tWon\tLost\tTied\n";
113        for (i = 0; i < NumTeams; i++) {
114          cout << L.teams[i].name << '\t'
115               << L.teams[i].won << '\t'
116               << L.teams[i].lost << '\t'
117               << L.teams[i].tied << '\n';
118        }
119      } 


*****  Sample Run  *****

50000
55000

/************************  Sample Run  ****************************

Enter team name => coots
Enter team name => ducks
Enter team name => eagles
Enter team name => finches
Enter team name => geese

5 teams initialized

Enter 11 scores:
<team #1> <score #1> <team #2> <score #2> => coots 5 ducks 2
<team #1> <score #1> <team #2> <score #2> => coots 3 eagles 7
<team #1> <score #1> <team #2> <score #2> => coots 1 finches 0
<team #1> <score #1> <team #2> <score #2> => coots 0 geese 0
<team #1> <score #1> <team #2> <score #2> => ducks 1 eagles 4
<team #1> <score #1> <team #2> <score #2> => ducks 5 finches 2
<team #1> <score #1> <team #2> <score #2> => ducks 2 geese 1
<team #1> <score #1> <team #2> <score #2> => eagles 7 finches 7
<team #1> <score #1> <team #2> <score #2> => eagles 8 geese 5
<team #1> <score #1> <team #2> <score #2> => finches 3 geese 2
<team #1> <score #1> <team #2> <score #2> => gooses 9 ducks 2

11 scores entered

Error: unable to find team: gooses

Name    Won     Lost    Tied
coots   2       1       1
ducks   2       2       0
eagles  3       0       1
finches 1       2       1
geese   0       3       1

******************************************************************/

C++ 的 reference 類似 C 的 point, 但 reference 必須起始化; 且 reference 通常用於 function arguments 和 return type. 最常見的例子就是 swap 的運用.

2011年12月22日 星期四

Getting Started (II)


Namespace std and the new Header filenames

The namespace keyword of C++ is used to group related data and functions. For example, if two sources provide a function called strcpy(). You may distinguish between them by prefacing strcpy() with the namespace, like VendorA::strcpy() or std::strcpy(). The namespace std is used to identify the standard ANSI/ISO symbols (functions, classes, and variables). The ANSI/ISO standards committee stipulated that standard header files would not have a filename extension. So, the header file, iostream.h will be identified as just iostream. The standard C header filenames, such as math.h, string.h, etc. will be prefaced with a c and the extension is dropped. Hence, math.h and string.h become cmath and cstring.

Example 1-2 namespace std and ANSI/ISO standard header files

1      // File: ex1-2.cpp - namespace std and the new header filenames
2     
3      #include <iostream>
4      #include <cmath>
5      #include <cstring>
6      #include <cstdlib>
7      #include <cctype>
8      using namespace std;
9     
10      // Create a namespace
11      namespace mystuff
12      {
13          int cout = 5;
14          double sqrt(double x) 
15          {
16              return x / 2.0;
17          }
18      }
19     
20      int main(void)
21      {
22          char cout[32] = "This is a bad idea";
23          char temp[80];
24          std::cout << "hey\n";
25          std::cout << "the square root of 2 is " << sqrt(2.) << endl;
26          strcpy(temp,"hello");
27          strcat(temp," there");
28          std::cout << strlen(temp) << temp << endl;
29          std::cout << atoi("4") << endl;
30          std::cout << toupper('a') << endl;
31          std::cout << (char)toupper('a') << endl;
32         
33          std::cout << mystuff::cout << ' ' << cout << endl;
34         
35          std::cout << sqrt(5.75) << ' ' << mystuff::sqrt(5.75)  << endl;
36          return 0;
37      }


******  Program Output  ******

hey
the square root of 2 is 1.41421
11hello there
4
65
A
5 This is a bad idea
2.39792 2.875

Note that symbols default to their local definitions first, then to std definitions.

main() and the return type

The C++ standard specifies that main() must return an int.  That is, you must define main() like

int main()
{

}

or

int main (void)
{

}

or

int main(int argc, char* argv[])
{

}

You may not define main() as

void main()
{

}

or

main()
{

}

You do not, however, have to end main() with a return statement. If the end of main() is reached without a return statement, a return of 0 is assumed.

The using directive and declaration

The keyword using is used as both a compiler directive and as a declaration. Throughout this text, the "using namespace std" directive directs the compiler to make available all of the "std" names.  So, for example,

#include <iostream>
using namespace std;

tells the compiler to recognize the names: cin, cout, endl, and others in whatever scope these two lines appear. Without the "using namespace std;" directive, the user would still have to qualify the the cin, cout, and endl identifiers as std::cin, std::cout, and std::endl;

Another approach is the using declaration, like this:

#include <iostream>

using std::cout;
using std::endl;



cout << …

Now, the user can use the identifiers cout and endl without the std namespace, but only those std identifiers. The using declaration adds an identifier to the current scope.
  1. 在 C++ 下 namespace 用來 group 相關的 data 與 function. 假始有兩個 source 都有 strcpy() 這個 function, 就可以用不同的 namespace 來區分.
  2. 在 C++ 標準中, main() 必須要 return int.
  3. 在 C++ 下 using 用來做為 compiler 指令或是宣告 .

2011年12月21日 星期三

Getting Started (I)


To get started with C++, we should dive right in, start writing code and see what's new. This section will address four differences between C and C++.
  • Writing comments in a C++ program
  • Using cin and cout for input and output to a C++ program (and #include <iostream>)
  • Declaring variables almost anywhere
  • Using type bool for true or false

Comments in a C++ program

In C, you learned to use the /* … */ style comment. Since C++ includes the C language syntax, you can, of course, use the same style comments, but C++ also includes its own style of writing a program comment. This is accomplished using //. The // can be used any place on a program line to mean that anything to the right of the // is intended to be a comment and not part of the program – not compiled. An entire line may be commented, like this:

// see, this is a comment consisting of an entire line
or part of a line like this:

if (b * b – 4 * a * c < 0) {        // make sure the determinant is not negative
You can use either C-style comments, /* … */, or C++ style comments or both in your program. The advantage of the C-style comment is that the comment can be long and span many lines, and the advantage of the C++ comment is that it's easier, two keystrokes instead of four. Besides, this is all about C++ anyway. There is one word of caution. Be careful of nesting the two styles. For example, this is OK.

/* this is a one-line comment */

/* this is
    a comment that
    goes on and on,
    and ends on this line */

/* Here's another comment // and what's this?
    Oh, who cares?
    That's all folks */

Now, here's the rub:

// this is OK

/* nothing wrong with
    this comment
*/

// This is a C++ style comment /* and now let's do a
    C-style comment */

/* Here's another
// screw up */

Do you see the problem? Just be careful.

cin and cout

In learning C, you probably started with scanf() and printf() for input and output. In C++, we will do the same thing with cin and cout. cin will be used for input from the keyboard and cout for output to the screen.

In C, it looks like this:

printf("Enter some number\n");
scanf("%d",&i);

In C++, like this:

cout << "Enter some number\n";
cin >> i;

scanf() and printf() are functions. cin and cout are not function they are things, or more precisely, objects. You can think of them as the keyboard and monitor (or screen). To be more precise, cin is an object of type istream and cout is an object of type ostream. And what about << and >>? These guys (guys is a technical term, more precisely, a male technical term) are operators, just like the + in x + y. And in case you wanted to know, operators, in C++ can be the same thing as functions.

So, of course, our two lines of code, displays Enter some number on the screen and the program stops, waiting for the user to enter a number. It acts just like the C code.

One more point, cin and cout are not free, just like printf() and scanf() are not free. To use printf() and scanf() you must include the header file, <stdio.h>. Similarly, in C++, for cin and cout, you will need to include the header file, <iostream>. Note that it is <iostream>, not <iostream.h>. We'll get to that later.

What exactly is cin and cout?

Consider the statements,

int age;
cin >> age;
cout << "I am " << age << " years old." << endl;

In C we would write,

int age;
scanf("%d",&age);
printf("I am %d years old.\n",39);

These two statements do the same thing. cin and cout are objects. This means that they are variables of a certain type (specially they are variables of type istream and ostream). They are not functions, like printf() and scanf(). The function part of the statements is the >> and << operators. And, while we're at it, endl is almost the same as \n.

Declaring variables where you want

In C you learned to declare variables at the beginning of a function and in C++ you can do the same thing. That, of course, would be too boring. So, there's another way. You can declare variables where you need them. Variables do not have to be declared at the beginning of your program, or the beginning of a function, or at the top of a block. They can be declared just before you use them. Of course, you can't declare them after you use them. For example, in C you would:

int x;
printf("Enter some number\n");
scanf("%d",&x);

And is C++, you can do this:

printf("Enter some number\n");
int x;
scanf("%d",&x);

There is the advantage or declaring variables at the top of a function. The reader of the code (that might be you in six months), knows where to look for variable declarations. On the other hand, being able to declare variable any old time allows you to write code without a lot of up front planning. That's a good thing, right?

Type bool

ANSI/ISO C++ includes a type called bool to store true-false values. This concept has been around forever in programming and in C and even C++.  I guess the only issue was settling on the name of the type. An obvious application might look like this:


bool rich;
rich = money > 1000000;
if (rich) {
  cout << "Whoopee!";
}

Here is the first example that demonstrates the some initial C++ concepts and some differences between C and C++.

Example 1-1

1      // File:  Ex1-1.cpp
2     
3      // Illustrates some of the basic differences between C and C++:
4      // Comments
5      // cin and cout for input and output
6      // declarations of variables almost anywhere
7      // use of type bool
8     
9      #include <iostream>        // instead of <stdio.h> or <iostream.h>
10      using namespace std;
11     
12      /* You can still use the old comment, */
13     
14      /* but you must be // very careful
15      about mixing them */
16     
17      // Your best bet is to use this style for 1 line or a partial line
18      /* And use this style when your comment
19      consists of multiple lines */
20     
21      int main (void)
22      {
23          cout << "hey";            // Why won't printf or puts work here?
24          //printf("hey");
25          //puts("hey");      // Can you use printf or puts in a C++ program?
26         
27          for (int k = 1; k < 5; k++)    // declare a variable when you need it
28          {
29              cout << k;
30          }
31          //cout << k;
32          cout << endl;            // print a carriage return (newline)
33         
34          cout << "Please enter your name => ";
35         
36          char name[10];            // I feel like declaring a variable
37         
38          cin >> name;
39         
40          cout << "Hey " << name << ", nice name." << endl;
41         
42          cout << endl;            // blank line
43         
44          cout << "Hey " << name << ", how old are you? ";
45         
46          int age;            // Declare another variable
47          cin >> age;
48         
49          bool IsOld = age > 35;
50          bool IsYoung = !IsOld;
51          cout << IsOld << ' ' << IsYoung << endl;
52         
53          if (IsOld) cout << name << ", you don't really look that old!\n;
54         
55          char dogs_name[10];
56          int cats;
57         
58          cout << "What's your dog's name and how many cats do you have? "
59              << endl;
60         
61          cin >> dogs_name >> cats;
62         
63          cout << "I'll bet " << dogs_name << " is a good dog and your "
64               << cats << " cat" << (cats>1?"s are":" is") << " nice too\n";
65         
66          {
67              // This is a block
68              int x = 5;    // x is local to this block
69              cout << x;
70          }
71         
72          // cout << x;     What would happen if you tried to print x now?
73         
74          return 0;
75      } 

*****  Sample Run  *****

hey1234
Please enter your name => Joe
Hey Joe, nice name.

Hey Joe, how old are you? 34
0 1
What's your dog's name and how many cats do you have?
Bart 2
I'll bet Bart is a good dog and your 2 cats are nice too
5

Note: cin is similar to scanf(), but does not require conversion specifiers and whitespace is a separator for multiple variables. cin does not require the address operator (&), like scanf().

<< ("left-shift" in C) is called the insertion operator. >> ("right shift") is called the extraction operator.

Note on for loops with MS Visual C++ 6.0: First of all, you should not be using MS Visual C++, it's too old. But, if you insist, the following code does not work according to the C++ "standard". The "standard" specifies that k will only "have scope" for the for loop, and after completion of the for loop, k will be undefined. MS Visual C++ 6.0 doesn't see it that way. You've been warned!

for (int k = 1; k < 5; k++)
{
   cout << k;
}

C++ 與 C 不同處:
  • comments 的寫法
  • 使用 cin and cout 來輸入和輸出 (#include <iostream>)
  • 隨時可以定義變數
  • 資料形態 bool 值為 true 或 false

Introduction to C++


What is C++ ?
  • it's "a better C"
  • it supports data abstraction
  • it's an Object-Oriented Programming Language

OOPLs have the following characteristics:
  • Encapsulation is the combining the data structure with actions. The data structure is used to represent the properties, the state, or characteristics of objects. The actions represent permissible behaviors of objects. These are controlled through the member functions that are attached to objects. It is through encapsulation that an object may be much more realistically represented - by including both the properties and the behavior in its definition. Further, the class designer can control the user interface much easier with this approach.
  • Inheritance is the ability to define a hierarchical relationship between objects that permits objects of a more specific class to inherit the properties (data) and behaviors (functions) of a more general class. For example, you might have dog objects with associated properties and behaviors and also beagle objects that will have all the properties and behaviors of dogs with a few more specific properties and behaviors of their own.
  • Polymorphism is the ability for different objects to interpret messages (functions) differently. For example, asking different shape objects (circle, square, rectangle, trapezoid) to return their area will result in different implementations. This is accomplished with virtual functions using "late (or dynamic) binding".
OOPLs support modular programming, ease of development and maintainability.

What is Object Oriented Programming?

C++ is an object oriented programming language. This means that the language is oriented toward programming with objects. Well, duh! Object oriented programming is a different approach than you learned in C. In C++, you create classes, after thinking about the design and what you want to accomplish, and, by the way, you usually don't get that part right on the first try. The class consists of members - data members or member functions. Member functions are also called methods. They're also called behaviors. Once you've created a class, you can declare (or define) a variable of that class type. That variable can be referred to as an object, or an instance (of the class type). You can then call a function using the object. Another way of saying that is, "you can apply the member function to the object". The member function is, well, first of all, it's just a function, meaning, it does something. Sometimes, the member function does something to the object. Sometimes, the member function does something for the object. Sometimes, the member function tells you something about the object. Sometimes, the member function is used to create the object (that's called a constructor). Sometimes, the member functions are used to destroy, or get rid of, the object (that's called a destructor). Some member functions look like operators (think + - / * -> % ! ~) when you called. C++ is all about accomplishing your task using objects and using the member functions that belong to the class(es). You can't really do anything with C++ that can't do with C, but once you get the hang of it, it's, in my opinion, a more natural way of getting the job done. Don't expect to immediately start coding using an object oriented approach, but may by the time you have completed this course, and have been exposed to dozens of examples in which classes have been used in many way, something should maybe ought to rub off.

C++ is "a better C", supports data abstraction, and is an effective OOPL primarily due to it use of classes. In C++, the class is the cornerstone of the language. Yes, C++ includes new syntax, new operators, new functions, and enhanced libraries, but it's really the implementation of classes, that give the language its identity.

Classes are:
  • a more powerful type of struct
  • data (properties, characteristics, state) and behaviors (methods)

For example, a dog class may contain data members such as breed, color, height, weight, number of feet (usually 4), eye color, etc. The class may also contain the behaviors that the dog can exhibit (the actions that it can perform, or the methods that it can apply). The dog may be able to sit, to run, to eat (that might affect its weight), etc. Sit, run, and eat would be member functions of the dog class. The class itself is not data.

An object is an instance (or occurrence) of a class. For example, you might have a dog, called Spot. Spot is an object. (Don't try to use this analogy on spouses!) Spot will possess all the properties of dog and can perform the behaviors of a dog. You might want Spot to sit down, so you'd say to spot: spot.sit(); That's, of course, assuming that Spot knows a little C++. The following C++ code illustrates these concepts.

class dog
{
  private:
    char breed[25];
    char color[20];
    int height;
    float weight;
    int feet;
    char eye_color[10];
  public:
    void sit(void);
    void eat(void);
    void run(void);
};

int main(void)
{
  dog spot;
  spot.sit();
  spot.eat();
  spot.run();
  return 0;
}


C++ 是比 C 好的 language, 主要的特性有:  Encapsulation, Inheritance, 與 Polymorphism.
C++ 的 data 稱為 member data; behavior 稱為 member function.

Some Thoughts On The Class


The following notes represent some on my thoughts about this course.

Why learn C++?
C++ is programming language that is very much in demand today, probably the language that is in most demand currently. It will definitely be a plus to have it on your resume.

What does the class cover?
CIS27 is a basic C++ class. Upon successful completion, you should be able to write C++ code, to read it, to use C++ reference manuals, and to step into an entry-level C++ programming situation. This is not an advanced class. It does not cover templates, exception handling, the Standard Template Library (STL), RTTI, writing your own manipulators, binary trees, and object oriented programming concepts. It is the basics, the language syntax, as well as language concepts. There are separate courses for the advanced concepts and object oriented programming.

What are the prerequisites?
Successful completion of a C programming class. That means a grade of A, B or C in such a class. You do not need any significant C programming experience, but you do need to be familiar with the basics, such as, variables, data types, for loops, while loops, input and output, file I/O, pointers, arrays, string functions, and basic ANSI standard functions. Do not expect to successfully complete this class without some C experience.

How can you be successful in this class?
"Successful" probably means an "A" in the class. An "A" means you can put it on your resume. It means that you could step into an entry-level C++ programming position and produce code within a short time. A "B" means that you missed a little, but with a little study and work you can be right there with the "A" types. A "C" means that there's hope, but you'll need to put in some time to catch up to the "A"s. Any other grade should repeat the course, probably after some C programming review. You're may be taking this class to help you get (or keep) a job. It's the "A"s that stand the best chance.

Now, back to the question. This class is 12 weeks long. It is a fairly short time commitment. You can be successful by doing the following:

  • Meet the prerequisites. Make sure you're comfortable with C. During the course, if you hear of a C concept that you are not familiar with, research it, or ask about it and get it.
  • Commit the time required for this course. You will need approximately 8 to 12 hours per week outside of class to complete the assignments and do the suggested reading. If you don't have the time, or don't commit to it, don't plan on an A or B in the class (and there isn't that many Cs received).
  • Come to class and be on time. Students who are on the road to "success", but have to miss a class, usually get behind. This probably translates into a full letter grade. If you "have to" miss a class session, plan on doing lots or reading and studying to make it up. Punctuality is especially important during the final and midterm. The tests have time limits. Final grades have dropped a full letter, because students showed up late for a test and didn't have enough time.
  • Get and read a textbook. The course notes are not a text book. They do not contain detailed explanations of C++ concepts. You should acquire a source for explanations beyond the examples in the notes. Check Appendix B for some possible books.
  • Do every assignment. Start early. Learn to break up the problem into small parts. Do one part at a time. Test your code as you proceed. This is particularly relevant when you start writing classes and member functions. If the assignment involves writing 2 classes, then do one at a time. Write one member function at a time, and test it. Make sure you understand what each part is supposed to accomplish. It not, ask. When you get stuck, try to solve the problem yourself. When you still can't get it, ask for help (see below).
  • Study for the tests. The tests are open book, but that's not the time to start reading. You should know exactly what topics are on the test. Do you know each one, or not? It's fair to ask for an explanation of some topic before the morning of the test. To study for a test shouldn't take long if you've kept up. You should be able to look at a list of topics, think about them, and consider whether or not you thoroughly understand the topic. Is there some syntax or notation that you do not understand about that topic?
  • Ask questions. In class and out of class. It's difficult to concentrate for 2+ hours of lecture (no matter how brilliant and entertaining the instructor is). You need to psyche yourself up to endure this. A good night's sleep the night before, some Starbuck's coffee, whatever it takes…
  • Use the lab time for some extra help, hand holding, showing you how to do it, explaining some concept in detail, giving you a hint on an assignment.
  • Talk to other students in the class about assignments, problems or various topics. This does not mean copying. This is not a course to practice typing or copying files. You are encouraged to discuss problems with other students, but not to copy their solution. This is just like a programming job. You will probably consult with coworkers regarding problems, but you cannot expect a coworker to do your work for you. If you need a hint on an assignment, ask the instructor. Remember, you will be taking the tests by yourself.
  • Asking Email Questions
  • You will need to ask a question (probably several) during the course. Do not hesitate to send me an email question. You should get a reply with 24 hours. Make sure you do get a reply, if not, send the question again, and if necessary, call me up. It's important that you understand what is a "fair" email question, a what is not.
  • It's fair to ask me to explain line 19 of example 2-5 or to explain what is meant by the 4th paragraph on page 317. It is not fair to ask to explain all 450 lines of example 2-7 or describe in an email note how constructors work or explain chapter 7 in the text. It is fair to ask what a copy constructor is.
The following are "fair" questions to ask about an assignment:
  • What is causing this error message: "Call to undefined function: strcopy()" on line 54 of my classX::funk() function? (The code is included)
  • What is the purpose of the goo() function in the XYZ class?
  • Can you give me a little hint about how to start writing the moo() function for ABC class?
  • Did we have an example similar to the poo() function?

These are "unfair" questions to ask about an assignment:
  • I don't understand what to do?
  • How do I get started?
  • I don't understand classes?
  • How do I write the moo() function for ABC class?
  • What is causing this error message: "Call to undefined function: strcopy()" on line 54 of my classX::funk() function? (The code is not included)
  • I've got a whole bunch of error messages, what do they mean?
  • What do these 3 error messages mean (messages included)? (2 is the limit)
  • Can I turn the assignment late?

When you submit an email question about an assignment, make sure you include all relevant parts of your code. If you're not sure whether or not to include part of your program, then include it. I would prefer that your code is included in the body of the note. If you want to use an attachment, my first preference is one file attachment (even though you may have a multi-file application).

要如何成功學會 C++? 努力,努力, 再努力!!

Preface


These notes are not intended to be a textbook. These pages represent numerous revisions of examples and notes of C++ concepts that I used for myself to gain an understanding of the language over the last dozen, or so, years. Since I learn best by looking at examples, I decided long ago to use these notes as a teaching tool. Every time I teach a class in C++ using these notes, I find mistakes, shortcomings, inaccuracies, and explanations needed. I make a list of corrections and notes to myself to rewrite this or that. And, even though I update the notes almost every time I teach the class, I never get it right. I do believe, however, that this makes me a better teacher – not being satisfied. I think that if I ever got it right, I'd have to quit (by then the language would be totally obsolete).

To make effective use of these notes, you have to learn to read examples. Reading an example of code, is not like reading anything else. It's like, you read a line of code, then you ask yourself:
  • What does this mean?
  • Why did the author do it this way?
  • What's that function?
  • What does that syntax mean?  Who's doing what to whom?
  • Is there another way of doing this?

Step back …

What's the point? (do I understand the concept(s) that Joe is trying to demonstrate)
This is a time-consuming and tedious process. (I can't read very much of someone else's code without getting antsy and distracted). As you become more experienced, you will be able to skip over "obvious" lines of code and concentrate on the gist of the example. (After you've seen #include <iostream> dozens of times, you won't even think about it). To be successful in reading examples, I recommend that you don't try to spend a lot of time doing it. Reading one or two examples and really getting it is better than trying to read six or ten examples and "kinda", "sorta", getting it.

Reading an example and getting it means that you "own the code". It's yours now. It doesn't mean memorizing it. It doesn't even mean that you don't have to look back see how to do that. It means that you understand how it works and you can reproduce, when needed, the concept or the logic (and take another look if you need to). After all, when you're cooking lasagna, you may have made it dozens of times, but it doesn't hurt to have the recipe next to you when you are making it for the fifty-first time.

針對每一行程式問自己:
  • 這是甚麼意思?
  • 作者為甚麼要這樣寫?
  • 這個 function 是甚麼?
  • 這個 syntax 是甚麼意思?
  • 有其他的方法可以達到一樣的目的嗎?

Course Information


Course Objectives
At the completion of the course, you should be able to write basic C++ programs which make use of the following:

  • reference variables
  • default arguments
  • dynamic memory allocation
  • classes
  • constructors and destructors
  • static data members and static member functions
  • function overloading and operator overloading
  • inheritance
  • polymorphism
  • C++ input/output classes and file I/O

Course Outline

  • Intro to C++    
  • Difference between C & C++: reference variables, default arguments, new and delete
  • Introduction to Classes               
  • Constructors and Destructors
  • More class features: this pointer, static members, friend functions
  • Function and Operator Overloading
  • Inheritance and Polymorphism
  • Input/Output and File I/O
  • C++ Applications & Review
  • Final

課程的目標與內容介紹