====== Static&Const ====== const是单词constant的简写,字面意思是常数、常量。用于变量修饰,表明这个变量不能被修改;用于指针修饰,表明指针的指向物不能被修改;用于方法修饰,表明这个方法不会对对象造成改变。 const int foo = 1; foo = 2; // compile time error const int* ptr = &foo; *ptr = 3 // compile time error int fuck = 0; ptr = &fuck; // this is OK *ptr = 123; // compile time error struct FooBar { int member; int MyMethod(int value) const { member = value; // compile time error } }; static很讨厌,有三个个完全不同的含义:用在全局变量,表明这个变量在每个编译单元有独自的实例: // foo.h static int a = 123;// foo.cpp #include "foo.h" int foo_func() { return a++; } // bar.cpp #include "foo.h" int bar_func() { return a++; } 如果你分别编译foo.cpp和bar.cpp,再把它们链接在一起,全局变量a会有两份,那两个函数会操纵不一样的a实例。用在函数里的局部变量,表明它的生存周期其实是全局变量,但仅在函数内可见: int get_global_id() { static int seed = 0; return seed++; } 每次访问这个函数的时候,会获得不同的int值。那个=0的操作仅在第一次访问时执行,其实是初始化而不是赋值。用在类成员,表明成员或者方法是类的,而不是对象实例的。 struct Foo { int a = 0; static int aaa = 0; static int bbb() { return 123456; } }; 每个Foo实例会只含有一个int a。bbb方法通过Foo::bbb()调用。 template T sum(const std::vector list,T initValue) { T result = initValue; for(auto& i:list) { result+=i; } return result; } ifstream fin(inputFile); //打开文件流操作 ofstream fin_new(outputFile); string line; int rollnum, count = 0; vector> vec; while (getline(fin, line)) //整行读取,换行符“\n”区分,遇到文件尾标志eof终止读取 { count++; cout << "line" << count<<":" << line << endl; //整行输出 istringstream sin(line); //将整行字符串line读入到字符串流istringstream中 vector row; //声明一个字符串向量 string word; while (getline(sin, word, ',')) //将字符串流sin中的字符读入到word字符串中,以逗号为分隔符 { row.push_back(word); //将刚刚读取的字符串添加到向量row中 } vector v1; for (int i = 0; i < row.size(); i++) { v1.push_back(stoi(row[i])); } vec.push_back(v1); } fin_new << vec[j][i]; fin_new.close(); fin.close(); //Point类,运算符重载 #include class Point { public: Point(double x,double y):_x(x),_y(y){}; bool operator >(const Point& p) { return (_x*_x+_y*_y)>(p._x*p._x+p._y*p._y); } bool operator ==(const Point& p) { return (_x*_x+_y*_y)==(p._x*p._x+p._y*p._y); } bool operator <(const Point& p) { return (_x*_x+_y*_y)<(p._x*p._x+p._y*p._y); } private: double _x; double _y; friend std::ostream& operator<<(std::ostream& os,const Point &point) { os<<"Point:("<