C++ 面向對象學習筆記[1]
阿新 • • 發佈:2018-07-30
app orange bsp 用途 hid srand com -h ret
#include <cassert> #include <cstdio> #include <cstdlib> #include <ctime> #include <iostream> #include <string> #include <vector> using namespace std; int RandomGenerator(int max) { assert(max <= RAND_MAX); srand(time(NULL)); int a = rand() % max;return a; } enum Fruit { apple, banana, pear, orange, watermelon, // the , is not necessary }; class Simple { private: int num; public: Simple(int a) { num = a; }; int get() { return num; }; }; struct BigInteger { static const int BASE = 100000000; static const intWIDTH = 8; vector<int> s; BigInteger(long long num = 0) { *this = num; } BigInteger operator=(long long num) { s.clear(); do { s.push_back(num % BASE); num /= BASE; } while (num > 0); return *this; } BigInteger operator=(const string &str) { s.clear();int x, len = (str.length() - 1) / WIDTH + 1; for (int i = 0; i < len; i++) { int end = str.length() - i * WIDTH; int start = max(0, end - WIDTH); sscanf(str.substr(start, end - start).c_str(), "%d", &x); s.push_back(x); } return *this; } }; BigInteger a; Fruit c = apple; // can without init Simple b(100); // = and () both okay int main() { a = 12345123; cout << b.get(); }
- 關於auto關鍵字:
- 在C++11前:意味著auto detect GC time,跟內存回收有關系
- 在C++11 :意味著自動判斷變量類型(或函數返回類型)
- 演示
auto a = 1.0; // 自動判斷類型 a 是一個double auto a;//錯誤,a不能未加初始化 int compare(auto a,auto b);//錯誤,auto無法根據上下文推斷 auto compare(int a,int b);//錯誤,auto無法根據上下文推斷 auto compare(int a,int b) -> int;//正確,但這種用途僅為了美觀
- 演示
- 在C++11後 : 另有變更,此處不討論
- 關於*this: http://www.learncpp.com/cpp-tutorial/8-8-the-hidden-this-pointer/
C++ 面向對象學習筆記[1]