1.C++基本语法


  
  1. #include <iostream> 
  2.  
  3. using namepase std; 
  4.  
  5. int main(){ 
  6.  
  7.   cout<<"Hello Word!"endl; 
  8.  
  9.   reutrn 0; 
  10.  

2.强制类型转换


  
  1. double answer; 
  2.  
  3. answer = static_cast<double>(9)/2; 

3.简单的文件操作


  
  1. #include <iostream> 
  2.  
  3. #include <fstream> 
  4.  
  5. int mian(){ 
  6.  
  7.   use namepace std; 
  8.  
  9.   ifstream in_stream; 
  10.  
  11.   ofstream out_stream; 
  12.  
  13.   in_stream.open("infile.dat"); 
  14.  
  15.   out_stream.open("outfile.dat"); 
  16.  
  17.   int first,second,third; 
  18.  
  19.   in_stream >> first >> second >> third; 
  20.  
  21.   out_stream << first + second + third << endl; 
  22.  
  23.   in_stream.close(); 
  24.  
  25.   out_stream.close(); 
  26.  
  27.   return 0; 
  28.  

4.C++终止程序代码


  
  1. exit(1); 

5.检查文件是否打开成功


  
  1. ifstream in_stream; 
  2.  
  3. if(in_stream.fail()){ 
  4.  
  5.   cout << "Opening failed"
  6.  
  7.   exit(1); 
  8.  

6.追加到文件


  
  1. ofstream fout; 
  2.  
  3. fout.open("data.txt",); 

7.eof函数


  
  1. if(!fin.eof()) 
  2.  
  3.   cout << "not done yet;"
  4.  
  5. else 
  6.  
  7.   cout << "end of file;"

8.结构体定义


  
  1. struct CDAccount{ 
  2.  
  3.   double balance; 
  4.  
  5.   double interest_rate; 
  6.  
  7. }; 
  8.  
  9. int main(){ 
  10.  
  11.   CDAccount account; 
  12.  
  13.   int interest; 
  14.  
  15.   account.balance = account.balance + interest; 
  16.  

9.定义类和成员函数


  
  1. class DayOfYear{ 
  2.  
  3. public
  4.  
  5.   void output(); 
  6.  
  7. }; 
  8.  
  9. void DayOfYear::output(){ 
  10.  
  11.   函数实现 
  12.  

10.构造函数


  
  1. 是类的成员函数,每个类都有成员函数。
  2. 初始化类的对象,比如:分配空间,赋初值。
  3. 特点:构造函数必须与类名相同、没有数据类型、没有返回值。
  4. 构造函数可重载,故一个类可有N个构造函数。
  5. 类给出构造函数时,系统不再产生构造函数。
  6. 构造函数在声明时自动调用。

11.无参数构造函数


  
  1. BankAccount account;//正确。 
  2. BankAccount account()//错误的。 

12.内存空间的释放


  
  1. BankAccount *myAcct; 
  2. myAcct = new BankAccount(); 
  3.  
  4. delete myAcct;//释放内存空间 
  5. 备注:delete只能释放自己分配的内存空间,new表示自己分配的内存空间。 
  6.  
  7. //错误例子 
  8. int x = 5; 
  9. delete x; 

13.友元函数


  
  1. class DayOfYear(){ 
  2. public
  3.   friend bool equal(DayOfYear date1,DayOfYear date2); 
  4. private
  5.   int month; 
  6.   int day; 
  7. }; 
  8. bool equal(DayOfYear date1,DayOfYear date2){ 
  9.   return (date1.month == date2.month && date1.day == date2.day);