C++ 面向对象学习笔记[1]
#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 int WIDTH = 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/
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
No sacrifice , no victory.