C++ 入門指南 V2.00 - 單元 4 範例及練習程式碼



pointer_demo.cpp


#include <iostream>
 
using namespace std;
 
int main(void) {
   // 設定 n 為整數 11
   int n = 11;
   cout << n << endl;
    
   // 設定 nPtr 為指向 n 的指標 
   int *nPtr = &n; // & 是取址運算子
   cout << nPtr << endl;
    
   // 設定 t 取得從 nPtr 位址指向的值
   int t = *nPtr; // * 是反參考運算子
   cout << t << endl;
     
   return 0;
}
 
/* 檔名: pointer_demo.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

pointer_demo2.cpp


#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
   // a 為字串變數
   string a = "There is no spoon.";
   cout << a << endl;
     
   // b 為對 a 的指標
   string *b = &a;
   cout << b << endl;
     
   // c 為對 a 的參考
   string &c = a;
   cout << c << endl;
     
   // d 為另一個指標
   string *d = new string("There is no spoon.");
   cout << d << endl;
     
   return 0;
}
 
/* 檔名: pointer_demo2.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

exercise0401.cpp


#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
   int a = 1;
   cout << "a: " << a << endl;    
    
   int *pa = &a;
   cout << "pa: " << pa << endl;
    
   return 0;
}
 
/* 檔名: exercise0401.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

exercise0402.cpp


#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
   int a = 1;
   cout << "a: " << a << endl;    
    
   int *pa = &a;
   cout << "pa: " << pa << endl;
    
   *pa = 2;
   cout << "a: " << a << endl;
    
   return 0;
}
 
/* 檔名: exercise0402.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

exercise0403.cpp


#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
   int a = 1;
   cout << "a: " << a << endl;    
    
   int *pa = &a;
   cout << "pa: " << pa << endl;
    
   *pa = 2;
   cout << "a: " << a << endl;
    
   int &ra = a;
   cout << "ra: " << ra << endl;
    
   return 0;
}
 
/* 檔名: exercise0403.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

exercise0404.cpp


#include <iostream>
#include <string>
 
using namespace std;
 
int main(void) {
   int a = 1;
   cout << "a: " << a << endl;    
    
   int *pa = &a;
   cout << "pa: " << pa << endl;
    
   *pa = 2;
   cout << "a: " << a << endl;
    
   int &ra = a;
   cout << "ra: " << ra << endl;
    
   ra = 3;
   cout << "a: " << a << endl;
    
   return 0;
}
 
/* 檔名: exercise0404.cpp 
   作者: Kaiching Chang 
   時間: 2014-5 */

the end

沒有留言: