3.94k likes | 4.08k Views
C++语言程序设计. 姚念民 哈尔滨工程大学计算机科学与技术学院 http://lucos.hrbeu.edu.cn. 课程基本信息. 总学时: 32 教材: Bruce Eckel . Thinking in C++ (特别版 影印版).北京:高等教育出版社, 2001 . Bjarne Stroustrop .C ++ 程序设计语言(特别版).北京:机械工业出版社, 2002 .. 1: Introduction to Objects. Why Object-Oriented Programming(OOP) What is OOP
E N D
C++语言程序设计 姚念民 哈尔滨工程大学计算机科学与技术学院 http://lucos.hrbeu.edu.cn
课程基本信息 • 总学时: 32 • 教材: • Bruce Eckel .Thinking in C++(特别版 影印版).北京:高等教育出版社,2001. • Bjarne Stroustrop.C++程序设计语言(特别版).北京:机械工业出版社,2002.
1: Introduction to Objects • Why Object-Oriented Programming(OOP) • What is OOP • Why to learn C++ • How to learn C++
Why Object-Oriented Programming(OOP) • To solve Software Crisis(软件危机) • More effective & productive • Provide a new software development method(软件开发方法) • provide tools for the programmer to represent elements in the problem space. • Easy to reuse software(软件重用) • Easy to maintain(维护) • Reduce hidden bugs(errors) • Easy to be adapted to the change(main goal of design pattern-设计模式)
What is OOP • Alan Kay summarized five basic characteristics of Smalltalk (upon which C++ is based ) • Everything is an object • A program is a bunch of objects telling each other what to do by sending messages. • Each object has its own memory made up of other objects • Every object has a type • All objects of a particular type can receive the same messages
What is OOP--in detail • Data abstraction • Data and operations are integrated as a new type — class • Automate the initialization & cleaning up • Encapsulation • hidden implementation • software reuse • Inheritance • composition or aggregation • Polymorphism • Virtual function • Upcast to base class • Template – source code reuse
Polymorphism Class Dog: public Pet{ void cry{ “wang wang” } Class Cat: public Pet{ void cry{ “miao miao” } Dog dog; Cat cat; Pet *pet = &dog; pet->cry(); pet = &cat; pet->cry(); If is a dog Then “wang wang” Else if is a cat Then “miao miao”
game-C&C,starcraft,warcraft • many objects • every object has its behaviors and figures • every turn • put modified objects into a container • go through the container • object->action(); • object->draw();
Why to learn C++ • Be used everywhere • Linux – g++ • Windows – VC++ • Almost can do everything • Application • Device driver • Operating System • To find a good job • To show your inteligence • To enjoy
A simple example of C++ //: C02:Hello.cpp // Saying Hello with C++ #include <iostream> // Stream declarations using namespace std; int main() { cout << "Hello, World!" << endl; } ///:~
Preprocessor Inlines #includes etc. Compiler Translates to machine code Associates calls with functions Linker Associates functions with definitions Compilation Object files: a.o Executable: a.out External Libraries, libc.so, libcs123.so
How to learn C++ • Programming • View the good source code • Open source project • Read classic book • Design Pattern • Effective C++ • …
What is an object in C++ Light lt; lt.on();
Extened example Light lt; lt.on(); It.off();
Object • Is a abstractive data type, it has • Name • Attributes • operations
Another example #include <iostream> #include <string> using namespace std; class Bird{ string hello; public: Bird():hello("hello world"){} /* Bird(){ hello = "Hello world"; }*/ void sayHello(){ cout<< hello << endl; // cout<< "Hello world" << endl; } }; int main(){ Bird bird; bird.sayHello(); }
// More streams features #include <iostream> using namespace std; int main() { // Specifying formats with manipulators: cout << "a number in decimal: " << dec << 15 << endl; cout << "in octal: " << oct << 15 << endl; cout << "in hex: " << hex << 15 << endl; cout << "a floating-point number: " << 3.14159 << endl; cout << "non-printing char (escape): " << char(27) << endl; } ///:~
void fun_1(int n) { if(n<2) cout<<n; if(n>=2) { fun_1(n/2); cout<<n%2; } }
Porcess of OOP • Phase 1: What are we making? • Phase 2: How will we build it? • Phase 3: Build the core • Phase 4: Iterate the use cases • Phase 5: Evolution--maintenance
In the previous generation of program design (called procedural design), this is called “creating the requirements analysis and system specification.” These, of course, were places to get lost; intimidatingly-named documents that could become big projects in their own right.
Phase 2: How will we build it? • In this phase you must come up with a design that describes what the classes look like and how they will interact. • Class-Responsibility-Collaboration (CRC) card • The name of the class. • The “responsibilities” of the class • The “collaborations” of the class • Five stages of object design • Object discovery • Object assembly • System construction • System extension • Object reuse
Phase 3: Build the core • This is the initial conversion from the rough design into a compiling and executing body of code that can be tested, and especially that will prove or disprove your architecture. • conversion from the rough design into a compiling and executing body of code that can be tested • is not a one-pass process, but rather the beginning of a series of steps that will iteratively build the system
Phase 4: Iterate the use cases • Once the core framework is running, each feature set you add is a small project in itself. You add a feature set during an iteration, a reasonably short period of development. • can reveal and resolve critical risks early • can see by the current state of the product exactly where everything lies
Phase 5: Evolution • This is the point in the development cycle that has traditionally been called “maintenance,” a catch-all term that can mean everything from “getting it to work the way it was really supposed to in the first place” to “adding features that the customer forgot to mention” to the more traditional “fixing the bugs that show up” and “adding new features as the need arises.” So many misconceptions have been applied to the term “maintenance” that it has taken on a slightly deceiving quality, partly because it suggests that you’ve actually built a pristine program and all you need to do is change parts, oil it, and keep it from rusting. Perhaps there’s a better term to describe what’s going on. • Maintenance • New requirements • Not right • Make better
Extreme programming--a new development method • Write tests first • Pair programming
Summary • OOP atributes: • Abstract data typing • Inheritance • polymorphism
2: Making & Using Objects This chapter will introduce enough C++ syntax and program construction concepts to allow you to write and run some simple object-oriented programs. In the subsequent chapter we will cover the basic syntax of C and C++ in detail.
Introducing strings • While a character array can be fairly useful, it is quite limited. It’s simply a group of characters in memory, but if you want to do anything with it you must manage all the little details. For example, the size of a quoted character array is fixed at compile time. If you have a character array and you want to add some more characters to it, you’ll need to understand quite a lot (including dynamic memory management, character array copying, and concatenation) before you can get your wish. This is exactly the kind of thing we’d like to have an object do for us.
The Standard C++ string class is designed to take care of (and hide) all the low-level manipulations of character arrays that were previously required of the C programmer. These manipulations have been a constant source of time-wasting and errors since the inception of the C language.
//: C02:HelloStrings.cpp(Page 99) // The basics of the Standard C++ string class #include <string> #include <iostream> using namespace std; int main() { string s1, s2; // Empty strings string s3 = "Hello, World."; // Initialized string s4("I am"); // Also initialized s2 = "Today"; // Assigning to a string s1 = s3 + " " + s4; // Combining strings s1 += " 8 "; // Appending to a string cout << s1 + s2 + "!" << endl; } ///:~
Reading and writing files • In C, the process of opening and manipulating files requires a lot of language background to prepare you for the complexity of the operations. However, the C++ iostream library provides a simple way to manipulate files, and so this functionality can be introduced much earlier than it would be in C.
// Copy one file to another, a line at a time #include <string> #include <fstream> using namespace std; int main() { ifstream in("Scopy.cpp"); // Open for reading ofstream out("Scopy2.cpp"); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "\n"; // ... must add it back } ///:~
// Read an entire file into a single string(P.102) #include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("FillString.cpp"); string s, line; while(getline(in, line)) s += line + "\n"; cout << s; } ///:~
Introducing vector • With strings, we can fill up a string object without knowing how much storage we’re going to need. The problem with reading lines from a file into individual string objects is that you don’t know up front how many strings you’re going to need – you only know after you’ve read the entire file. To solve this problem, we need some sort of holder that will automatically expand to contain as many string objects as we care to put into it.
// Copy an entire file into a vector of string(P. 105) #include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { vector<string> v; ifstream in("Fillvector.cpp"); string line; while(getline(in, line)) v.push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v.size(); i++) cout << i << ": " << v[i] << endl; } ///:~
Summary • The intent of this chapter is to show you how easy object-oriented programming can be – if someone else has gone to the work of defining the objects for you. In that case, you include a header file, create the objects, and send messages to them. If the types you are using are powerful and well-designed, then you won’t have to do much work and your resulting program will also be powerful.
homework • 2. Using Stream2.cpp and Numconv.cpp as guidelines, create a program that asks for the radius of a circle and prints the area of that circle. You can just use the ‘*’ operator to square the radius. Do not try to print out the value as octal or hex (these only work with integral types). • 8. Create a vector<float> and put 25 floating-point numbers into it using a for loop. Display the vector.
3: The C in C++ • Since C++ is based on C, you must be familiar with the syntax of C in order to program in C++, just as you must be reasonably fluent in algebra in order to tackle calculus.
Controlling execution • if-else • while • do-while • for • switch
while • The expression is evaluated once at the beginning of the loop and again before each further iteration of the statement. // Guess a number (demonstrates "while") #include <iostream> using namespace std; int main() { int secret = 15; int guess = 0; // "!=" is the "not-equal" conditional: while(guess != secret) { // Compound statement cout << "guess the number: "; cin >> guess; } cout << "You guessed it!" << endl; } ///:~
do-while • The do-while is different from the while because the statement always executes at least once, even if the expression evaluates to false the first time. // The guess program using do-while #include <iostream> using namespace std; int main() { int secret = 15; int guess; // No initialization needed here do { cout << "guess the number: "; cin >> guess; // Initialization happens } while(guess != secret); cout << "You got it!" << endl; } ///:~
for // Display all the ASCII characters // Demonstrates "for" #include <iostream> using namespace std; int main() { for(int i = 0; i < 128; i = i + 1) if (i != 26) // ANSI Terminal Clear screen cout << " value: " << i << " character: " << char(i) // Type conversion << endl; } ///:~
switch #include <iostream> using namespace std; int main() { bool quit = false; // Flag for quitting while(quit == false) { cout << "Select a, b, c or q to quit: "; char response; cin >> response; switch(response) { case 'a' : cout << "you chose 'a'" << endl; break; case 'b' : cout << "you chose 'b'" << endl; break; case 'c' : cout << "you chose 'c'" << endl; break; case 'q' : cout << "quitting menu" << endl; quit = true; break; default : cout << "Please use a,b,c or q!" << endl; } } } ///:~
Introduction to C++ references • Pointers work roughly the same in C and in C++, but C++ adds an additional way to pass an address into a function. This is pass-by-reference and it exists in several other programming languages so it was not a C++ invention.