C++ 1 STL 83 C++ hello.c #include <iostream> int main (void) { std::cout << "Hello, World !" << std::endl; return 0; } hello.cpp #include <iostream> //#include <stdio.h> #include <cstdio> int main (void) { std::cout << "Hello, World !" << std::endl; printf ("Hello, World ! "); int i; std::cin >> i; std::cerr << i << std::endl; std::cout << 10 << ' ' << 1.23 << ' ' << "cccc" << std::endl; i = 1; i = i << 2; std::cout << i << std::endl; return 0; } bool.cpp #include <iostream> using namespace std; int main (void) { bool b = true; cout << boolalpha << b << endl; b = !b; cout << b << endl; cout << sizeof (b) << endl; b = 1000; cout << b << endl; b = 3.14; cout << b << endl; b = "hello, world"; cout << b << endl; b = NULL; cout << b << endl; bool male = true; return 0; } string.cpp #include <iostream> #include <cstdio> using namespace std; int main (void) { string s1 = "hello"; cout << s1 << endl; s1 += " "; s1 += "world"; cout << s1 << endl; s1 = "达内科技"; cout << s1 << endl; string s2 = "达内"; cout << (s1 > s2) << endl; cout << s1.length () << endl; string s3 = "./string.cpp"; FILE* fp = fopen (s3.c_str (), "r"); s3[2] = 'S'; cout << s3 << endl; for (size_t i = 0; i < s3.length (); ++i) cout << s3[i] << endl; return 0; } struct.cpp #include <iostream> using namespace std; struct Student { // 成员变量 char name[128]; int age; int score; // 成员函数 void who (void) { cout << "我是" << name << ",今年" << age << "岁。今天考试得了" << score << "分。" << endl; } }; int main (void) { Student s = {"张飞", 25, 85}, *p = &s; cout << s.name << ' ' << s.age << ' ' << s.score << endl; cout << p->name << ' ' << p->age << ' ' << p->score << endl; s.who (); p->who (); Student t = {"赵云", 22, 45}; t.who (); return 0; } union.cpp #include <iostream> #include <cstdio> using namespace std; int main (void) { union { int n; char c[4]; }; n = 0x12345678; for (int i = 0; i < 4; ++i) printf ("%#x ", c[i]); cout << endl; return 0; } enum.cpp #include <iostream> using namespace std; enum Color {RED, GREEN, BLUE}; void foo (int n) {} void bar (Color c) {} int main (void) { cout << RED << ' ' << GREEN << ' ' << BLUE << endl; // Color c = 0; // ERROR Color c = RED; int n = c; cout << n << endl; foo (RED); // bar (0); // ERROR return 0; } op.cpp #include <iostream> using namespace std; int main (void) <% int a<::> = <%13, 21, 37, 49, 58%>; int b<::> = <%79, 63, 45, 31, 16%>; for (int i = 0; i < 5; ++i) cout << (a<:i:> bitand b<:i:>) + ((a<:i:> xor b<:i:>) >> 1) << ' '; cout << endl; %> ns.cpp #include <iostream> using namespace std; //int var = 9999; namespace ns { int var = 0; void fun (void) { std::cout << "ns的fun函数" << std::endl; } } namespace ns { struct type { int x; char y[256]; }; } namespace nt { void fun (void) { std::cout << "nt的fun函数" << std::endl; } } namespace nu { int x = 1234; void fun (void) { std::cout << "nu的fun函数" << std::endl; } } int y = 8888; namespace nv { int x = 5678; int y = 9999; void foo (void) { cout << y << endl; cout << ::y << endl; } } namespace ns1 { int a = 1; namespace ns2 { int a = 2; namespace ns3 { int a = 3; } } } int main (void) { std::cout << ns::var << std::endl; ns::fun (); struct ns::type t = {100, "张飞"}; std::cout << t.x << ' ' << t.y << std::endl; using namespace ns; var++; std::cout << var << std::endl; fun (); using namespace nt; nt::fun (); ns::fun (); cout << var << endl; using namespace nv; using nu::x; cout << "### " << x << endl; nu::fun (); // using nv::x; nv::foo (); cout << ns1::a << endl; cout << ns1::ns2::a << endl; cout << ns1::ns2::ns3::a << endl; namespace ns123 = ns1::ns2::ns3; cout << ns123::a << endl; return 0; } day02 add.c #include "add.h" int add (int a, int b) { return a + b; } add.h #ifndef _ADD_H #define _ADD_H int add (int, int); #endif // _ADD_H main.cpp #include <iostream> using namespace std; extern "C" { #include "add.h" } int main (void) { cout << add (100, 200) << endl; return 0; } add.cpp #include "add.h" int add (int a, int b) { return a + b; } add.h #ifndef _ADD_H #define _ADD_H #ifdef __cplusplus extern "C" { #endif int add (int, int); #ifdef __cplusplus } #endif #endif // _ADD_H main.c #include <stdio.h> #include "add.h" int main (void) { printf ("计算结果:%d ", add (100, 200)); return 0; } defargs.cpp #include <iostream> using namespace std; void foo (int a, int b = 1000) { cout << a << ' ' << b << endl; } void bar (int a = 100+900) { cout << a << endl; } int b = 1000; void hum (int a = b) { cout << a << endl; } //void fun (int a, int b = a) {} // ERROR void fun (int a = 1000); void fff (int a, int b = 1000, int c = 2000) { cout << a << ' ' << b << ' ' << c << endl; } void fff (int a) { cout << a << endl; } int main (void) { foo (123, 456); foo (123); // foo (123, 1000); bar (); // bar (1000); hum (); fun (); fff (123, 456); // fff (123, , 456); // fff (123); // ERROR return 0; } void fun (int a /* = 1000 */) { cout << a << endl; } dummy.cpp #include <iostream> using namespace std; int add (int a, int, int c) { return a + c; } void foo (int) {} void bar (void) {} void bar (int) {} int main (void) { cout << add (100, 200, 300) << endl; return 0; } fptr.cpp #include <iostream> using namespace std; double foo (int n) { cout << 1 << endl; } char* foo (float f) { cout << 2 << endl; } int main (void) { double (*p1) (int) = foo; char* (*p2) (float) = foo; cout << (void*)p1 << ' ' << (void*)p2 << endl; p1 (3.14f); // 1 p2 (10); // 2 foo (3.14f); // 2 foo (10); // 1 return 0; } inline.cpp #include <iostream> using namespace std; inline double square (double x) { return x * x; } int main (void) { cout << square (3.0) << endl; // cout << 3.0 * 3.0 << endl; return 0; } match.cpp #include <iostream> using namespace std; void funa (char* p) { cout << 1 << endl; } void funa (char const* p) { cout << 2 << endl; } void funb (char const* p, char c) { cout << 1 << endl; } void funb (char*p, int n) { cout << 2 << endl; } void func (char c) { cout << 1 << endl; } void func (int n) { cout << 2 << endl; } void func (long l) { cout << 3 << endl; } void fund (int n, void* p) { cout << 1 << endl; } void fund (double d, ...) { cout << 2 << endl; } int main (void) { char* p; funa (p); // 完全匹配优于常量转换 char c; funb (p, c); // 常量转换优于升级转换 short h; func (h); // 升级转换优于标准转换 // 但也没有必要过分升级 double d; void* pv; fund (d, pv); // 可变长参数表匹配度最低 return 0; } new.cpp #include <cstdio> #include <cstring> #include <iostream> using namespace std; int main (void) { // int* p = (int*)malloc (sizeof (int)); int* p = new int; *p = 1234; cout << *p << endl; // free (p); delete p; p = new int (); // 用0初始化 cout << *p << endl; delete p; p = new int (5678); // 指定初始值 cout << *p << endl; delete p; p = NULL; delete p; // p = (int*)malloc (5 * sizeof (int)); p = new int[5] {10, 20, 30, 40, 50}; // C++11 /* for (int i = 0; i < 5; ++i) p[i] = (i+1)*10; */ for (int i = 0; i < 5; ++i) cout << p[i] << ' '; cout << endl; delete[] p; // !!! int (*prow)[4] = new int[3][4]; // int *prow[4] for (int i = 0; i < 3; ++i) for (int j = 0; j < 4; ++j) prow[i][j] = (i+1)*10+(j+1); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) cout << prow[i][j] << ' '; cout << endl; } delete[] prow; int (*ppage)[4][5] = new int[3][4][5]; // int (*ppage)[4][5] = // (int (*)[4][5])malloc (60 * sizeof (int)); delete[] ppage; try { p = new int[0xFFFFFFFF]; // ... delete[] p; } catch (exception& ex) { cout << ex.what () << endl; perror ("new"); // return -1; } // char* pool = new char[1024]; // 分配内存池 char pool[1024]; int* pn = new (pool) int (123); // 定位分配 char* ps = new (pool+4) char[15]; strcpy (ps, "Hello, World !"); double* pd = new (pool+19) double (3.14); cout << *pn << ' ' << ps << ' ' << *pd << endl; // delete[] pool; // 释放内存池 return 0; } overload.cpp #include <iostream> using namespace std; void foo (void) { cout << "1" << endl; } void foo (int n) { cout << "2" << endl; } void foo (int* n) { cout << "3" << endl; } void foo (int n, double d) { cout << "4" << endl; } void foo (double n, int d) { cout << "5" << endl; } //void foo (double d, int n) {} // ->15 //int foo (void) {} // ->3 int main (void) { foo (); // 1 foo (100); // 2 int n; foo (&n); // 3 foo (n, 1.13); // 4 foo (1.13, n); // 5 return 0; } scope.cpp #include <iostream> using namespace std; void foo (void) { cout << 1 << endl; } namespace ns1 { void foo (int a) { cout << 2 << endl; } namespace ns2 { void foo (int a, int b) { cout << 3 << endl; } void bar (void) { foo (10, 20); ns1::foo (10); ::foo (); } } } namespace nsa { void fun (int x) { cout << 'a' << endl; } } namespace nsb { void fun (double x) { cout << 'b' << endl; } } int main (void) { ns1::ns2::bar (); using namespace nsa; using namespace nsb; fun (100); // a fun (1.2); // b using nsa::fun; fun (100); // a fun (1.2); // a using nsb::fun; fun (100); // a fun (1.2); // b return 0; } day03 const.cpp #include <iostream> using namespace std; int main (void) { int volatile const x = 100; int& r = const_cast<int&> (x); // char& c = const_cast<char&> (x); // x = 200; r = 200; cout << &r << ' ' << (void*)&x << endl; cout << r << endl; cout << x << endl; // cout << 100 << endl; return 0; } ref.cpp #include <iostream> using namespace std; int main (void) { int a = 10; int& b = a; ++b; cout << a << ' ' << b << endl; cout << &a << ' ' << &b << endl; int& c = b; ++c; cout << a << ' ' << b << ' ' << c << endl; cout << &c << endl; // int const& d = a; const int& d = a; cout << d << endl; cout << &d << endl; // d = 20; // d++; a = 20; b++; --c; cout << d << endl; // int& e = 10; int x = 100, y = 200, z = 300; cout << x + y + z << endl; // x + y = z; int const& e = x + y; cout << e << endl; int const& f = 10; cout << f << endl; // int& g; // ERROR int& g = *new int (100); cout << g << endl; // 100 delete &g; // 此时g就是一个野引用 return 0; } refarg.cpp #include <cmath> #include <cstring> #include <iostream> using namespace std; void foo (int a) { cout << "foo:" << &a << endl; ++a; cout << "a = " << a << endl; // 124 } void bar (int& a) { cout << "bar:" << &a << endl; ++a; cout << "a = " << a << endl; // 124 } double rect (double w, double h, double* c, double& s) { *c = (w + h) * 2; s = w * h; return sqrt (w * w + h * h); } struct Student { char name[64]; char addr[256]; char mbox[128]; }; void insert (Student const& student) { cout << student.name << "," << student.addr << "," << student.mbox << endl; // strcpy (student.name, "sb"); } int main (void) { int x = 123; cout << "main:" << &x << endl; foo (x); cout << "x = " << x << endl; // 123 bar (x); cout << "x = " << x << endl; // 124 double w = 3, h = 4, c, s, t; t = rect (w, h, &c, s); cout << "周长:" << c << endl; cout << "面积:" << s << endl; cout << "对角线:" << t << endl; Student student = {"张飞", "达内科技", "zhangfei@tarena.com.cn"}; insert (student); cout << student.name << endl; return 0; } refarr.cpp #include <iostream> using namespace std; void foo (int a[12]) { cout << sizeof (a) << endl; // 4 } void bar (int a[]) { cout << sizeof (a) << endl; // 4 } void hum (int* a) { cout << sizeof (a) << endl; // 4 } void fun (int (&a)[12]) { cout << sizeof (a) << endl; // 48 } void fff (int (*a)[12]) { cout << sizeof (*a) << endl; // 48 } int main (void) { int a[12]; cout << sizeof (a) << endl; // 48, a整体 foo (a); // a首地址 bar (a); // a首地址 hum (a); // a首地址 fun (a); // a整体 fff (&a);// a整体 return 0; } reffun.cpp #include <iostream> using namespace std; int add (int x, int y) { return x + y; } int main (void) { // 古典写法 int (*pfunc) (int, int) = &add; cout << (*pfunc) (100, 200) << endl; // 现代写法 int (*pfun2) (int, int) = add; cout << pfun2 (100, 200) << endl; // 函数引用 int (&rfunc) (int, int) = add; cout << rfunc (100, 200) << endl; return 0; } refret.cpp #include <iostream> using namespace std; struct A { int data; int& foo (void) { return data; } }; int& bar (int& a) { return a; } int& hum (void) { static int n = 123; return n; } int& fun (void) { int m = 456; return m; } int main (void) { A a = {100}; cout << a.data << endl; // 100 a.foo () = 200; cout << a.data << endl; // 200 int x; bar (x) = 1000; cout << x << endl; // 1000 int& r = hum (); cout << r << endl; // 123 fun (); cout << r << endl; // 456 return 0; } reinter.cpp #include <iostream> using namespace std; int main (void) { char c[] = {0x78, 0x56, 0x34, 0x12}; int* n = reinterpret_cast<int*> (c); cout << hex << showbase << *n << endl; double x = 3.14; double* p = &x; int i = reinterpret_cast<int> (p); char* h = reinterpret_cast<char*> (i); p = reinterpret_cast<double*> (h); cout << *p << endl; return 0; } static.cpp #include <iostream> using namespace std; int main (void) { short x = 10; void* v = &x; short* p = static_cast<short*> (v); // int* q = static_cast<int*> (p); return 0; } swap.cpp #include <iostream> using namespace std; void swap1 (int x, int y) { int z = x; x = y; y = z; } void swap2 (int* x, int* y) { int z = *x; *x = *y; *y = z; } void swap3 (int& x, int& y) { int z = x; x = y; y = z; } void swapp (char const** x, char const** y) { char const* z = *x; *x = *y; *y = z; } void swapr (char const*& x, char const*& y) { char const* z = x; x = y; y = z; } int main (void) { int x = 100, y = 200; // swap1 (x, y); // swap2 (&x, &y); swap3 (x, y); cout << x << ' ' << y << endl; char const* p = "hello"; char const* q = "world"; // swapp (&p, &q); swapr (p, q); cout << p << ' ' << q << endl; return 0; } day04 cast.cpp #include <iostream> using namespace std; class Integer { public: Integer (void) { m_data = 0; } explicit Integer (int data) { cout << "Integer类型转换构造函数" << endl; m_data = data; } int m_data; }; void foo (Integer const& i) { cout << i.m_data << endl; } Integer bar (void) { return static_cast<Integer> (400); } int main (void) { Integer i; cout << i.m_data << endl; // 0 i = static_cast<Integer> (200); cout << i.m_data << endl; // 200 int x = 300; foo (static_cast<Integer> (x)); cout << bar ().m_data << endl; return 0; } constructor.cpp #include <iostream> using namespace std; class Student { public: /* Student (string const& name, int age) { m_name = name; m_age = age; } Student (string const& name) { m_name = name; m_age = 20; } // 缺省构造函数 Student (void) { m_name = ""; m_age = 20; } */ Student (string const& name = "", int age=20) { m_name = name; m_age = age; } void print (void) { cout << m_name << "," << m_age << endl; } private: string m_name; int m_age; }; int main (void) { // Student s1 ("张飞", 25); Student s1 = Student ("张飞", 25); Student s2 ("赵云"); // Student s3 (); // 被编译器误解为函数声明 Student s3; s1.print (); s2.print (); s3.print (); cout << "----------------" << endl; Student* s4 = new Student ("关羽", 40); Student* s5 = new Student ("刘备"); Student* s6 = new Student (); Student* s7 = new Student; s4->print (); s5->print (); s6->print (); s7->print (); delete s7; delete s6; delete s5; delete s4; cout << "----------------" << endl; Student sa[3]; for (size_t i = 0; i < 3; ++i) sa[i].print (); cout << "----------------" << endl; Student sc[] = { Student ("曹操", 35), Student ("孙权"), Student ()}; for (size_t i = 0; i < 3; ++i) (sc+i)->print (); cout << "----------------" << endl; Student* sd = new Student[3]; for (size_t i = 0; i < 3; ++i) i[sd].print (); delete[] sd; cout << "----------------" << endl; Student* se = new Student[3] { Student ("黄忠", 50), Student ("马超"), Student ()}; for (size_t i = 0; i < 3; ++i) se[i].print (); delete[] se; return 0; } copy.cpp #include <iostream> using namespace std; class Point3D { public: Point3D (int x = 0, int y = 0, int z = 0) { m_x = x; m_y = y; m_z = z; } /* Point3D (Point3D const& that) { cout << "Point3D拷贝构造函数" << endl; m_x = that.m_x; m_y = that.m_y; m_z = that.m_z; } */ void print (void) { cout << "三维点(" << m_x << ',' << m_y << ',' << m_z << ')' << endl; } private: int m_x; int m_y; int m_z; }; void foo (Point3D p) { p.print (); } Point3D bar (void) { Point3D p (40, 50, 60); cout << "bar:" << &p << endl; return p; } int main (void) { Point3D p1 (10, 20, 30); p1.print (); Point3D p2 = p1; p2.print (); foo (p2); Point3D const& p = bar (); cout << "main:" << &p << endl; return 0; } defcon.cpp #include <iostream> using namespace std; class A { public: A (void) { cout << "A的缺省构造函数" << endl; m_data = 0; } A (int data) { cout << "A的有参构造函数" << endl; m_data = data; } int m_data; }; class B { public: B (int i = 0) { m_i = i; } int m_i; // 基本类型成员 A m_a; // 类类型成员 }; int main (void) { B b; cout << b.m_i << endl; return 0; } init.cpp #include <iostream> using namespace std; class Student { public: Student (string const& name = "", int age = 20) : m_name (name), m_age (age) { } void print (void) { cout << m_name << "," << m_age << endl; } private: string m_name; int m_age; }; class A { public: A (int data) : m_data (data) {} int m_data; }; class B { public: B (int data) : m_a (data) {} A m_a; }; int g_x = 5678; class C { public: C (void) : m_i (1000), m_r (g_x) {} int const m_i; int& m_r; }; class D { public: D (string const& str) : m_str (str), m_len (str.length ()) {} int m_len; string m_str; }; struct Date { int year; int mon; int day; }; class E { public: E (int a[], Date d) : m_a {a[0], a[1], a[2]}, /*m_d {d.year, d.mon, d.day}*/ m_d (d) {} int m_a[3]; Date m_d; }; int main (void) { Student s1 ("张飞", 25); Student s2 ("赵云"); Student s3; s1.print (); s2.print (); s3.print (); B b (1234); cout << b.m_a.m_data << endl; C c; cout << c.m_i << ' ' << c.m_r << endl; D d ("ABCDEFG"); cout << d.m_len << ' ' << d.m_str << endl; int a[3] = {123, 456, 789}; Date dt = {2015, 1, 8}; E e (a, dt); cout << e.m_a[0] << ' ' << e.m_a[1] << ' ' << e.m_a[2] << endl; cout << e.m_d.year << '-' << e.m_d.mon << '-' << e.m_d.day << endl; return 0; } student.cpp #include <iostream> using namespace std; class Student { public: // 构造函数 Student (string const& name, int age, int no) { cout << "我出生了!呵呵!" << endl; m_name = name; m_age = age; m_no = no; } void eat (string const& food) { cout << "我叫" << m_name << ",正在吃" << food << endl; } void sleep (int time) { cout << "我今年" << m_age << "岁,睡了" << time << "小时" << endl; } void learn (string const& course) { cout << "我的学号是" << m_no << ",现在学" << course << "课" << endl; } void setName (string const& name) { if (name == "二") cout << "拒绝接受不雅的姓名!" << endl; else m_name = name; } void setAge (int age) { if (age < 0) cout << "拒绝接受非法的年龄!" << endl; else m_age = age; } void setNo (int no) { if (no < 0 || 10000 < no) cout << "拒绝接受错误的学号!" << endl; else m_no = no; } private: string m_name; int m_age; int m_no; }; int main (void) { Student s1 ("张飞", 25, 1001); s1.setName ("二"); s1.setAge (-1); s1.setNo (1001000); s1.eat ("面条"); s1.sleep (1); s1.learn ("C++"); Student* s2 = new Student ("赵云", 20, 1002); s2->eat ("烙饼"); s2->sleep (2); s2->learn ("UNIX-C"); delete s2; return 0; } student.h #ifndef _STUDENT_H #define _STUDENT_H #include <string> using namespace std; // 声明学生类 class Student { public: // 构造函数 Student (string const& name, int age, int no); void eat (string const& food); void sleep (int time); void learn (string const& course); void setName (string const& name); void setAge (int age); void setNo (int no); private: string m_name; int m_age; int m_no; }; #endif // _STUDENT_H student.cpp // 实现学生类 #include <iostream> using namespace std; #include "student.h" // 构造函数 Student::Student (string const& name, int age, int no) { cout << "我出生了!呵呵!" << endl; m_name = name; m_age = age; m_no = no; } void Student::eat (string const& food) { cout << "我叫" << m_name << ",正在吃" << food << endl; } void Student::sleep (int time) { cout << "我今年" << m_age << "岁,睡了" << time << "小时" << endl; } void Student::learn (string const& course) { cout << "我的学号是" << m_no << ",现在学" << course << "课" << endl; } void Student::setName (string const& name) { if (name == "二") cout << "拒绝接受不雅的姓名!" << endl; else m_name = name; } void Student::setAge (int age) { if (age < 0) cout << "拒绝接受非法的年龄!" << endl; else m_age = age; } void Student::setNo (int no) { if (no < 0 || 10000 < no) cout << "拒绝接受错误的学号!" << endl; else m_no = no; } main.cpp #include "student.h" int main (void) { Student s1 ("张飞", 25, 1001); s1.setName ("二"); s1.setAge (-1); s1.setNo (1001000); s1.eat ("面条"); s1.sleep (1); s1.learn ("C++"); Student* s2 = new Student ("赵云", 20, 1002); s2->eat ("烙饼"); s2->sleep (2); s2->learn ("UNIX-C"); delete s2; return 0; } day05 array.cpp #include <iostream> using namespace std; class Array { public: Array (size_t size) : m_array (new int[size]), m_size (size) { cout << "构造函数:" << this << endl; } ~Array (void) { cout << "析构函数:" << this << endl; delete[] m_array; } int& at (size_t i) { if (i >= m_size) throw string ("下标溢出!"); return m_array[i]; } int const& at (size_t i) const { return const_cast<Array*> (this)->at (i); } private: int* m_array; size_t m_size; }; Array g_a (3); int main (void) { cout << "main函数开始了!" << endl; { Array a (5); for (size_t i = 0; i < 5; ++i) a.at (i) = i + 1; for (size_t i = 0; i < 5; ++i) cout << a.at (i) << ' '; cout << endl; } cout << "再见喽!" << endl; Array* a = new Array (10); // a = malloc (sizeof (Array)); // Array::Array (a); // ... delete a; // Array::~Array (a); // free (a); return 0; } cfunc.cpp #include <iostream> using namespace std; class A { public: void foo (void) {} // 非常函数 // void foo (A* this) {} void bar (void) const {} // 常函数 // void bar (A const* this) {} void hum (void) { // void hum (A* this) { cout << "hum函数的非常版本" << endl; } void hum (void) const { // void hum (A const* this) { cout << "hum函数的常版本" << endl; } void fun (void) const { cout << "fun函数的常版本" << endl; } }; int main (void) { A a; // 非常对象 a.foo (); // foo (&a) a.bar (); // bar (&a) A const& r = a; // 常对象 // r.foo (); // foo (&r) r.bar (); // bar (&r) A const* p = &a; // 常对象 // p->foo (); // foo (p) p->bar (); // bar (p) a.hum (); // hum (&a); r.hum (); // hum (&r); p->hum (); // hum (p); a.fun (); r.fun (); p->fun (); return 0; } const.cpp #include <iostream> using namespace std; class Student { public: Student (string const& name = "", int age = 0) : m_name (name), m_age (age), m_times (0) {} // 常函数 void print (void) const { // void print (Student const* this) { cout << m_name << "," << m_age << endl; // this->m_name = "sb"; // this->m_age = -1; // ++const_cast<Student*> (this)->m_times; ++m_times; } string m_name; int m_age; mutable int m_times; }; void print (Student const& student) { cout << student.m_name << "," << student.m_age << endl; // student.m_name = "sb"; // student.m_age = -1; } int main (void) { Student student ("张飞", 25); print (student); print (student); student.print (); student.print (); cout << student.m_times << endl; return 0; } cp.cpp #include <iostream> using namespace std; class Integer { public: Integer (int i) : m_i (new int (i)) {} /* 缺省的支持浅拷贝的拷贝构造函数 Integer (Integer const& that) : m_i (that.m_i) {} */ // 自定义支持深拷贝的拷贝构造函数 Integer (Integer const& that) : m_i (new int (*that.m_i)) {} ~Integer (void) { if (m_i) { delete m_i; m_i = NULL; } } /* 缺省的支持浅拷贝的拷贝赋值运算符函数 Integer& operator= (Integer const& rhs) { cout << "拷贝赋值运算符函数" << endl; m_i = rhs.m_i; } */ // 自定义支持深拷贝的拷贝赋值运算符函数 Integer& operator= (Integer const& rhs) { if (&rhs != this) { // 防止自赋值 int* i = new int (*rhs.m_i); delete m_i; // 释放旧资源 m_i = i; // 分配新资源 // 拷贝新内容 } return *this; // 返回自引用 } int* m_i; }; int main (void) { Integer i1 (100); cout << *i1.m_i << endl; Integer i2 = i1; // 拷贝构造 cout << *i2.m_i << endl; *i1.m_i = 200; cout << *i2.m_i << endl; Integer i3 (300); i1 = i3; // 拷贝赋值 // i1.operator= (i3); // 拷贝赋值运算符函数 cout << *i1.m_i << endl; // 300 cout << *i3.m_i << endl; // 300 *i3.m_i = 400; cout << *i1.m_i << endl; // 300 cout << *i3.m_i << endl; // 400 cout << i1.m_i << ' ' << i3.m_i << endl; int x = 10, y = 20, z = 30; (x = y) = z; cout << x << ' ' << y << ' ' << z << endl; // 30 20 30 (i1 = i2) = i3; // i1.operator= (i2).operator= (i3) i1 = i1; return 0; } defdes.cpp #include <iostream> using namespace std; class A { public: A (void) { cout << "A构造" << endl; } ~A (void) { cout << "A析构" << endl; } }; class B { private: A m_a; }; class C { public: C (void) : m_a (new A) {} ~C (void) { delete m_a; } private: A* m_a; }; int main (void) { // B b; C c; return 0; } object.cpp #include <cstring> #include <iostream> using namespace std; class Student { public: Student (char const* name, int age) : // Student (Student* this, char const* name, // int age) m_age (age) { cout << "构造函数中的this:" << this << endl; strcpy (m_name, name); } void print (void) { cout << "this:" << this << endl; cout << m_name << "," << m_age << endl; } /* void print (Student* this) { cout << this->m_name << "," << this->m_age << endl; } */ private: char m_name[256]; int m_age; }; int main (void) { Student s1 ("张飞", 25); // s1.Student (&s1, "张飞", 25); cout << "&s1:" << &s1 << endl; s1.print (); // s1.print (&s1); cout << sizeof (s1) << endl; Student s2 ("赵云", 20); cout << "&s2:" << &s2 << endl; s2.print (); // s2.print (&s2); return 0; } question.cpp #include <iostream> using namespace std; class Student; class Teacher { public: void educate (Student* student); void reply (char const* answer) { m_answer = answer; } private: string m_answer; }; class Student { public: void ask (char const* question, Teacher* teacher) { cout << "问题:" << question << endl; teacher->reply ("我不知道!"); } }; void Teacher::educate (Student* student) { student->ask ("什么是this指针?", this); cout << "回答:" << m_answer << endl; } class A { public: A (void) { cout << "我出生了!" << endl; } ~A (void) { cout << "我要死了!" << endl; } void work (void) { cout << "我工作了..." << endl; delete this; // 自我毁灭 } }; int main (void) { Teacher t; Student s; t.educate (&s); (new A)->work (); return 0; } string.cpp #include <cstring> #include <iostream> using namespace std; class String { public: String (char const* str = NULL) : m_str (strcpy ( new char [strlen (str ? str : "") + 1], str ? str : "")) {} String (String const& that) : m_str (strcpy ( new char [strlen (that.m_str) + 1], that.m_str)) {} ~String (void) { if (m_str) { delete[] m_str; m_str = NULL; } } String& operator= (String const& rhs) { } char const* c_str (void) const { return m_str; } private: char* m_str; }; int main (void) { String s1 ("hello"); cout << s1.c_str () << endl; String s2 = s1; cout << s2.c_str () << endl; String s3 ("world"); s2 = s3; cout << s2.c_str () << endl; return 0; } this.cpp #include <iostream> using namespace std; class A { public: A (int* data, int numb) : numb (numb) { for (int i = 0; i < numb; ++i) this->data[i] = data[i]; // this->numb = numb; } int data[1024]; int numb; }; class B { public: B (void) : m_counter (0) {} B& inc (void) { ++m_counter; return *this; // 返回自引用 } int m_counter; }; int main (void) { int data[5] = {10, 20, 30, 40, 50}; A a (data, 5); for (int i = 0; i < a.numb; ++i) cout << a.data[i] << ' '; cout << endl; B b; b.inc ().inc ().inc (); cout << b.m_counter << endl; // 3 return 0; } day06 account.cpp #include <iostream> using namespace std; class Account { public: Account (double balance) : m_balance (balance) {} double settle (void) { return m_balance *= (1 + m_inter); } static void setInter (double inter) { m_inter = inter; } private: double m_balance; static double m_inter; }; double Account::m_inter = 0.01; int main (void) { Account a1 (1000), a2 (10000); cout << a1.settle () << ' ' << a2.settle () << endl; Account::setInter (0.05); cout << a1.settle () << ' ' << a2.settle () << endl; return 0; } complex1.cpp #include <iostream> using namespace std; class Complex { public: Complex (int r = 0, int i = 0) : m_r (r), m_i (i) {} void show (void) const { cout << m_r << '+' << m_i << 'i' << endl; } // 第一个const:返回常对象,禁止对返回值赋值 // 第二个const:支持常对象形式的右操作数 // 第三个const:支持常对象形式的左操作数 Complex const operator+ ( Complex const& rhs) const { return Complex (m_r + rhs.m_r, m_i + rhs.m_i); } private: int m_r; int m_i; friend Complex const operator- ( Complex const&, Complex const&); }; Complex const operator- (Complex const& lhs, Complex const& rhs) { return Complex (lhs.m_r - rhs.m_r, lhs.m_i - rhs.m_i); } int main (void) { Complex c1 (1, 2), c2 (3, 4), c3 (5, 6); c1.show (); c2.show (); c3.show (); // Complex c4 = c1.operator+ (c2).operator+ (c3); Complex c4 = c1 + c2 + c3; c4.show (); /* int a, b, c; (a + b) = c; */ // (c1 + c2) = c3; Complex const c5 (7, 8); (c1 + c5).show (); // c1.operator+ (c5) (c5 + c1).show (); // c5.operator+ (c1) c4 = c3 - c2; // c4 = ::operator- (c3, c2); c4.show (); return 0; } complex2.cpp #include <iostream> using namespace std; class Complex { public: Complex (int r = 0, int i = 0) : m_r (r), m_i (i) {} void show (void) const { cout << m_r << '+' << m_i << 'i' << endl; } Complex& operator+= (Complex const& rhs) { m_r += rhs.m_r; m_i += rhs.m_i; return *this; } friend Complex& operator-= (Complex& lhs, Complex const& rhs) { lhs.m_r -= rhs.m_r; lhs.m_i -= rhs.m_i; return lhs; } private: int m_r; int m_i; }; int main (void) { Complex c1 (1, 2), c2 (3, 4), c3 (5, 6); c1 += c2; // c1.operator+= (c2) c1.show (); // 4+6i (c1 += c2) += c3; c1.show (); // 12+16i /* int a = 1, b = 3, c = 5; (a += b) += c; cout << a << endl; // 9 */ c1 -= c3; c1.show (); // 7+10i return 0; } complex3.cpp #include <cmath> #include <iostream> using namespace std; class Complex { public: Complex (int r = 0, int i = 0) : m_r (r), m_i (i) {} Complex const operator- () const { return Complex (-m_r, -m_i); } friend int operator~ (Complex const& opd) { return sqrt (opd.m_r * opd.m_r + opd.m_i * opd.m_i); } friend istream& operator>> (istream& lhs, Complex& rhs) { return lhs >> rhs.m_r >> rhs.m_i; } friend ostream& operator<< (ostream& lhs, Complex const& rhs) { return lhs << rhs.m_r << '+' << rhs.m_i << 'i'; } private: int m_r, m_i; }; int main (void) { Complex c1, c2; cin >> c1 >> c2; // ::operator>> (::operator>> (cin, c1), c2); cout << c1 << ' ' << c2 << endl; // ::operator<< ( // ::operator<< ( // ::operator<< ( // ::operator<< (cout, c1), ' '), c2), // endl); cout << -c1 << endl; cout << ~c2 << endl; return 0; } complex4.cpp #include <iostream> using namespace std; class Complex { public: Complex (int r = 0, int i = 0) : m_r (r), m_i (i) {} void show (void) const { cout << m_r << '+' << m_i << 'i' << endl; } // 成员函数形式的前++ Complex& operator++ (void) { ++m_r; ++m_i; return *this; } // 全局函数形式的前-- friend Complex& operator-- (Complex& opd) { --opd.m_r; --opd.m_i; return opd; } // 成员函数形式的后++ Complex const operator++ (int) { Complex old = *this; ++*this; return old; } // 全局函数形式的后-- friend Complex const operator-- (Complex& opd, int) { Complex old = opd; --opd; return old; } friend ostream& operator<< (ostream& lhs, Complex const& rhs) { return lhs << rhs.m_r << '+' << rhs.m_i << 'i'; } private: int m_r, m_i; }; int main (void) { int x = 10; ++x = 20; cout << x << endl; // 20 ++++++++x; // ++(++(++(++x))) cout << x << endl; // 24 cout << ++x << endl; // 25 cout << x << endl; // 25 Complex c1 (1, 2), c2 (30, 40); cout << ++c1 << endl; // 2+3i // cout << c1.operator++ () << endl; cout << c1 << endl; // 2+3i ++c1 = c2; cout << c1 << endl; // 30+40i ++++++++c1; cout << c1 << endl; // 34+44i cout << --c1 << endl; // 33+43i cout << c1 << endl; // 33+43i ------c1; cout << c1 << endl; // 30+40i // x++ = 30; // x++++++++; cout << c1++ << endl; // 30+40i // cout << c1.operator++ (0) << endl; cout << c1 << endl; // 31+41i cout << c1-- << endl; // 31+41i cout << c1 << endl; // 30+40i return 0; } membptr.cpp #include <cstring> #include <iostream> using namespace std; class Student { public: Student (string const& name = "", int age = 0) : m_name (name), m_age (age) {} void who (void) const { cout << m_name << "," << m_age << endl; } bool m_sex; double m_score; string m_name; int m_age; }; int main (void) { string Student::*pname = &Student::m_name; int Student::*page = &Student::m_age; Student s ("张飞", 25), *p = &s; // .* - 成员指针解引用运算符 cout << s.*pname << "," << s.*page << endl; // ->* - 间接成员指针解引用运算符 cout << p->*pname << "," << p->*page << endl; int i; memcpy (&i, &pname, 4); cout << i << endl; memcpy (&i, &page, 4); cout << i << endl; void (Student::*pwho) (void) const = &Student::who; memcpy (&i, &pwho, 4); cout << hex << showbase << i << endl; (s.*pwho) (); (p->*pwho) (); return 0; } others.cpp #include <iostream> using namespace std; class A { public: int& operator[] (int i) { return m_array[i]; } int const& operator[] (int i) const { return const_cast<A&> (*this)[i]; } private: int m_array[10]; }; class B { public: int operator() (int x, int y) const { return x + y; } }; class Integer { public: Integer (int i = 0) : m_i (i) {} operator int (void) const { return m_i; } int m_i; }; int main (void) { A a; a[0] = 1; // a.operator[] (0) = 1 a[1] = 2; // a.operator[] (1) = 2 cout << a[0] << ' ' << a[1] << endl; A const& cr = a; cout << cr[0] << endl; // cr[0]++; B b; cout << b (123, 456) << endl; // cout << b.operator() (123, 456) << endl; Integer x; x = 123; cout << x.m_i << endl; int y; y = x; cout << y << endl; return 0; } single.cpp #include <iostream> using namespace std; // 单例模式 class A { public: void work (void) { cout << "使用对象的功能..." << endl; } static A& getInstance (void) { // return m_a; if (! m_a) m_a = new A; return *m_a; } private: A (void) {}; A (const A&) {}; // static A m_a; static A* m_a; }; //A A::m_a; A* A::m_a = NULL; /* A g_a; A g_b; A g_c; */ int main (void) { A& a = A::getInstance (); a.work (); A& b = A::getInstance (); b.work (); cout << &a << ' ' << &b << endl; return 0; } static.cpp #include <iostream> using namespace std; static int g = 100; // 静态全局变量 static void foo (void) { // 静态全局函数 static int i = 10; // 静态局部变量 int j = 10; cout << ++i << ' ' << ++j << endl; } class A { public: A (void) : m_memb (300) {} static int m_smemb; // 静态成员变量 int m_memb; static void foo (void) { // 静态成员函数 cout << m_smemb << endl; // cout << m_memb << endl; // 错误 // cout << this << endl; // 错误 // bar (); // 错误 } void bar (void) { cout << m_memb << endl; cout << m_smemb << endl; foo (); } private: static int m_spriv; static int const m_i = 10; // 只有常静态成员变量 // 才能在类的声明部分 // 初始化 }; int A::m_smemb = 200; // 定义静态成员变量 int A::m_spriv = 400; int main (void) { foo (); // 11 11 foo (); // 12 11 foo (); // 13 11 A a1, a2; cout << &a1.m_smemb << ' ' << &a1.m_memb<<endl; cout << &a2.m_smemb << ' ' << &a2.m_memb<<endl; ++a1.m_smemb; cout << a2.m_smemb << endl; // 201 ++a1.m_memb; cout << a2.m_memb << endl; // 300 cout << A::m_smemb << endl; // 201 // cout << A::m_memb << endl; // 错误 // cout << a1.m_spriv << endl;// 私有无法访问 // cout << A::m_spriv << endl; return 0; } string.cpp #include <cstring> #include <iostream> using namespace std; class String { public: String (char const* str = NULL) : m_str (strcpy ( new char [strlen (str ? str : "") + 1], str ? str : "")) {} String (String const& that) : m_str (strcpy ( new char [strlen (that.m_str) + 1], that.m_str)) {} ~String (void) { if (m_str) { delete[] m_str; m_str = NULL; } } /* 菜鸟 void operator= (String const& rhs) { m_str = new char[strlen (rhs.m_str) + 1]; strcpy (m_str, rhs.m_str); }*/ /* 小鸟 String& operator= (String const& rhs) { if (&rhs != this) { delete[] m_str; m_str = strcpy ( new char[strlen (rhs.m_str) + 1], rhs.m_str); } return *this; }*/ /* 大鸟 String& operator= (String const& rhs) { if (&rhs != this) { char* str = new char[strlen (rhs.m_str) + 1]; delete[] m_str; m_str = strcpy (str, rhs.m_str); } return *this; }*/ // 老鸟 String& operator= (String const& rhs) { if (&rhs != this) { String str (rhs); swap (m_str, str.m_str); } return *this; } char const* c_str (void) const { return m_str; } private: char* m_str; }; int main (void) { String s1 ("hello"); cout << s1.c_str () << endl; String s2 = s1; cout << s2.c_str () << endl; String s3 ("world"); s2 = s3; cout << s2.c_str () << endl; return 0; } day07 abc.cpp #include <iostream> using namespace std; class A { public: A (void) : m_x (0) { cout << "A缺省构造" << endl; } A (int x) : m_x (x) { cout << "A有参构造" << endl; } A (A const& that) : m_x (that.m_x) { cout << "A拷贝构造" << endl; } A& operator= (A const& rhs) { cout << "A拷贝赋值" << endl; m_x = rhs.m_x; return *this; } ~A (void) { cout << "A析构函数" << endl; } friend ostream& operator<< (ostream& lhs, A const& rhs) { return lhs << rhs.m_x; } private: int m_x; }; class B : public A { public: B (void) : /*A (), */m_y (0) { cout << "B缺省构造" << endl; } B (int x, int y) : A (x), m_y (y) { cout << "B有参构造" << endl; } B (B const& that) : A (that), m_y (that.m_y) { cout << "B拷贝构造" << endl; } B& operator= (B const& rhs) { cout << "B拷贝赋值" << endl; A::operator= (rhs); m_y = rhs.m_y; return *this; } ~B (void) { cout << "B析构函数" << endl; } friend ostream& operator<< (ostream& lhs, B const& rhs) { return lhs << static_cast<A const&> (rhs) << '+' << rhs.m_y << 'i'; } private: int m_y; }; int main (void) { cout << "-------- 1 --------" << endl; B b1 (100, 200); cout << "-------- 2 --------" << endl; B b2 = b1; cout << "-------- 3 --------" << endl; B b3; b3 = b2; cout << "-------- 4 --------" << endl; cout << b3 << endl; cout << "-------- 5 --------" << endl; A* p = new B; delete p; // A::~A cout << "-------- 6 --------" << endl; return 0; } access.cpp #include <iostream> using namespace std; class A { public: int m_pub; void pub (void) { cout << "pub" << endl; } protected: int m_pro; void pro (void) { cout << "pro" << endl; m_pri = 100; cout << m_pri << endl; } private: int m_pri; void pri (void) { cout << "pri" << endl; } }; class B : public A { public: void foo (void) { m_pub = 0; pub (); m_pro = 0; pro (); // m_pri = 0; // pri (); } }; int main (void) { B b; b.m_pub = 1; b.pub (); // b.m_pro = 1; // b.pro (); // b.m_pri = 1; // b.pri (); cout << sizeof (b) << endl; b.foo (); return 0; } diamond.cpp #include <iostream> using namespace std; class A { public: A (int data) : m_data (data) {} protected: int m_data; }; class B : virtual public A { public: B (int data) : A (data) {} void set (int data) { m_data = data; } }; class C : virtual public A { public: C (int data) : A (data) {} int get (void) { return m_data; } }; class D : public B, public C { public: D (int data) : B (-9), C (23), A (data) {} }; int main (void) { D d (1000); cout << d.get () << endl; d.set (2000); cout << d.get () << endl; cout << sizeof (D) << endl; // 12 cout << sizeof (B) << endl; // cout << sizeof (C) << endl; // cout << sizeof (A) << endl; // return 0; } hide.cpp #include <iostream> using namespace std; class A { public: void foo (void) { cout << "A::foo" << endl; } void bar (void) {} int hum; }; class B : public A { public: using A::foo; void foo (int x) { cout << "B::foo" << endl; A::hum = 10; } int bar; typedef unsigned int hum; }; int main (void) { B b; // b.A::foo (); b.foo (); b.foo (100); b.A::bar (); b.A::hum = 10; return 0; } hst.cpp #include <iostream> using namespace std; // 人类 class Human { public: Human (string const& name = "", int age = 0) : m_name (name), m_age (age) {} void eat (string const& food) const { cout << m_name << "吃" << food << endl; } void sleep (int hours) const { cout << m_name << "睡" << hours << "小时" << endl; } void old (void) const { cout << "我今年" << m_age << "岁" << endl; } protected: string m_name; int m_age; }; // 学生类 class Student : public Human { public: Student (string const& name, int age, int no) : Human (name, age), m_no (no) {} void learn (string const& course) const { cout << "我的学号" << m_no << ",正在学习" << course << endl; } private: int m_no; }; // 教师类 class Teacher : public Human { public: Teacher (string const& name, int age, double salary) : Human (name, age), m_salary (salary) {} void teach (string const& course) const { cout << "我的工资" << m_salary << ",正在讲授" << course << endl; } private: double m_salary; }; int main (void) { Student s1 ("张飞", 25, 1001); s1.eat ("包子"); s1.sleep (5); s1.old (); s1.learn ("C++"); cout << sizeof (s1) << endl; Teacher t1 ("曹操", 60, 50000); t1.eat ("煎饼"); t1.sleep (2); t1.old (); t1.teach ("标C"); cout << sizeof (t1) << endl; Human* h = &s1; // 向上造型安全,皆然性 h->eat ("KFC"); h->sleep (10); h->old (); // h->learn ("UNIX"); Student* s = static_cast<Student*> (h); s->learn ("UNIX"); Human h1 ("刘备", 40); s = static_cast<Student*> (&h1); s->learn ("Win32"); return 0; } pointer.cpp #include <iostream> using namespace std; class B { public: B (void) : m_data (1234) {} void foo (void) { cout << "B::foo" << endl; } string operator() (string const& x = "我在吃", string const& y = "好吃的") const { return x + y; } int m_data; }; class A { public: A (B* b) : m_b (b) {} B* operator-> (void) const { return m_b; } B& operator* (void) const { return *m_b; } private: B* m_b; }; int main (void) { B b; A a (&b); cout << a->m_data << endl; // cout << a.operator->()->m_data << endl; a->foo (); // a.operator->()->foo (); cout << (*a).m_data << endl; // cout << a.operator*().m_data << endl; (*a).foo (); // a.operator*().foo (); cout << b ("我在学习", "标准C++编程") << endl; // cout << b.operator() ( // "我在学习", "标准C++编程") << endl; cout << b () << endl; return 0; } sp.cpp #include <iostream> using namespace std; class Phone { public: Phone (string const& no) : m_no (no) {} void call (string const& no) const { cout << m_no << "打电话给" << no << endl; } int m_a; int foo (int x, int y) const { return x + y; } private: string m_no; }; class Player { public: Player (string const& media) : m_media (media) {} void play (string const& clip) const { cout << m_media << "播放器播放" << clip << endl; } typedef int m_a; int foo (int x, int y, int z) const { return x + y + z; } private: string m_media; }; class Computer { public: Computer (string const& os) : m_os (os) {} void run (string const& app) const { cout << "在" << m_os << "系统上运行" << app << endl; } void m_a (void) {} private: string m_os; }; class SmartPhone : public Phone, public Player, public Computer { public: SmartPhone (string const& no, string const& media, string const os) : Phone (no), Player (media), Computer (os) {} int m_a; using Phone::foo; using Player::foo; }; int main (void) { SmartPhone sp ("13910110072", "MP4", "iOS"); sp.call ("01062332018"); sp.play ("小苹果"); sp.run ("LOL"); Phone* phone = &sp; // Player* player = reinterpret_cast<Player*>(&sp); Player* player = &sp; Computer* computer = &sp; cout << &sp << ' ' << phone << ' ' << player << ' ' << computer << endl; phone->call ("01062332018"); player->play ("小苹果"); computer->run ("LOL"); SmartPhone* psp = static_cast<SmartPhone*> (player); cout << psp << endl; psp = static_cast<SmartPhone*> (computer); cout << psp << endl; sp.Phone::m_a = 20; SmartPhone::Player::m_a i; sp.m_a = 10; sp.Computer::m_a (); // cout << sp.Phone::foo (100, 200) << endl; // cout << sp.Player::foo (100, 200, 300) << endl; cout << sp.foo (100, 200) << endl; cout << sp.foo (100, 200, 300) << endl; return 0; } xyz.cpp #include <iostream> using namespace std; class X { public: int m_pub; protected: int m_pro; private: int m_pri; }; class Y1 : public X { // 公子 }; class Z1 : public Y1 { public: void foo (void) { m_pub = 0; m_pro = 0; // m_pri = 0; } }; class Y2 : protected X { // 保子 }; class Z2 : public Y2 { public: void foo (void) { m_pub = 0; m_pro = 0; // m_pri = 0; } }; class Y3 : private X { // 私子 }; class Z3 : public Y3 { public: void foo (void) { // m_pub = 0; // m_pro = 0; // m_pri = 0; } }; int main (void) { Y1 y1; y1.m_pub = 0; // y1.m_pro = 0; // y1.m_pri = 0; Y2 y2; // y2.m_pub = 0; // y2.m_pro = 0; // y2.m_pri = 0; Y3 y3; // y3.m_pub = 0; // y3.m_pro = 0; // y3.m_pri = 0; X* x = &y1; // x = &y2; // x = &y3; return 0; } day08 dao.cpp #include <iostream> using namespace std; class Employee { public: string m_name; int m_no; int m_age; // ... }; class Dao { public: virtual void insert ( Employee const& emp) const = 0; }; class OracleDao : public Dao { public: void insert (Employee const& emp) const { cout << "向Oracle数据库插入记录" << endl; } }; class SQLServerDao : public Dao { public: void insert (Employee const& emp) const { cout << "向SQLServer数据库插入记录" << endl; } }; void business (Dao const& dao) { // 通过Pro*C向Oracle数据库插入一条记录 // 通过ODBC向SQLServer数据库插入一条记录 Employee emp; // ... dao.insert (emp); // 面向抽象编程 } int main (void) { // business (OracleDao ()); business (SQLServerDao ()); return 0; } dc.cpp #include <iostream> #include <stdexcept> using namespace std; class A { public: virtual void foo (void) {} }; class B : public A {}; class C : public B {}; class D {}; int main (void) { B b; A* pa = &b; cout << "pa = " << pa << endl; // pa实际指向B类对象,转换成功 B* pb = dynamic_cast<B*> (pa); cout << "pb = " << pb << endl; // pa没有指向C类对象,转换失败,安全 C* pc = dynamic_cast<C*> (pa); cout << "pc = " << pc << endl; try { A& ra = b; C& rc = dynamic_cast<C&> (ra); } catch (exception& ex) { cout << "转换失败:" << ex.what () << endl; } // pa没有指向D类对象,转换失败,安全 D* pd = dynamic_cast<D*> (pa); cout << "pd = " << pd << endl; // B是A的子类,转换成功 pb = static_cast<B*> (pa); cout << "pb = " << pb << endl; // C是A的间接子类,转换成功,危险 pc = static_cast<C*> (pa); cout << "pc = " << pc << endl; // D与A没有亲缘关系,转换失败,安全 // pd = static_cast<D*> (pa); // cout << "pd = " << pd << endl; // 编译期、运行期都不检查,永远成功,危险 pb = reinterpret_cast<B*> (pa); cout << "pb = " << pb << endl; pc = reinterpret_cast<C*> (pa); cout << "pc = " << pc << endl; pd = reinterpret_cast<D*> (pa); cout << "pd = " << pd << endl; return 0; } override.cpp #include <iostream> using namespace std; /* 全局函数不能是虚函数 virtual void foo (void) {} */ class A { public: /* 静态成员函数不能是虚函数 virtual static void foo (void) {} */ void foo (void) { cout << "A::foo" << endl; } }; class B : public A { public: virtual void foo (void) { // 隐藏A::foo cout << "B::foo" << endl; } }; class C : public B { public: void foo (void) { // 覆盖B::foo cout << "C::foo" << endl; } }; class D : public C { public: void foo (void) { // 覆盖C::foo cout << "D::foo" << endl; } }; class E { public: virtual void foo (void) {} }; class F : public E { public: virtual void bar (void) {} // 函数名不一致 virtual void foo (int x) {} // 形参表不一致 virtual void foo (void) const {} // 常属性不一致 void foo (void) {} // 覆盖E::foo }; class X {}; class Y : public X {}; class Z {}; class G { public: virtual void foo (void) {} virtual int bar (void) {} virtual X hum (void) {} virtual /*Y**/X* fun (void) {} }; class H : public G { public: /*int*/void foo (void) {} /*long*/int bar (void) {}; /*Y*/X hum (void) {} /*Z**//*X**/Y* fun (void) {} }; class I { public: virtual void foo (void) { cout << "I::foo" << endl; } }; class J : public I { private: void foo (void) { // 覆盖I::foo cout << "J::foo" << endl; } }; int main (void) { B b; A& a = b; a.foo (); C c; B& rb = c; rb.foo (); D d; B* pb = &d; pb->foo (); J j; // j.foo (); I& i = j; i.foo (); return 0; } parser.cpp #include <iostream> using namespace std; class Text {}; class Rect {}; class Image {}; class Parser { public: void parse (char const* filename) { // 解析出文本 Text text; showText (text); // 解析出矩形 Rect rect; showRect (rect); // 解析出图像 Image image; showImage (image); // ... } private: virtual void showText (Text const&) = 0; virtual void showRect (Rect const&) = 0; virtual void showImage (Image const&) = 0; // ... }; class RenderForWindows : public Parser { private: void showText (Text const& text) { cout << "显示文本" << endl; } void showRect (Rect const& rect) { cout << "显示矩形" << endl; } void showImage (Image const& image) { cout << "显示图像" << endl; } // ... }; /* class RenderForMac : public Parser { ... }; */ int main (void) { RenderForWindows render; // RenderForMac render; render.parse ("xxx.pdf"); return 0; } poly.cpp #include <iostream> using namespace std; class A { public: A (void) { /*this->*/foo (); // A::foo } ~A (void) { /*this->*/foo (); // A::foo } virtual void foo (void) { cout << "A::foo" << endl; } void bar (void) { /*this->*/foo (); // B::foo } }; class B : public A { public: void foo (void) { cout << "B::foo" << endl; } }; int main (void) { B b; // A a = b; A& a = b; a.foo (); b.bar (); return 0; } shape.cpp #include <iostream> using namespace std; class Shape { // 抽象类 public: Shape (int x, int y) : m_x (x), m_y (y) {} /* virtual void draw (void) const { cout << "图形(" << m_x << ',' << m_y << ')' << endl; } */ // 纯虚函数 virtual void draw (void) const = 0; protected: int m_x; int m_y; }; class Rect : public Shape { public: Rect (int x, int y, int w, int h) : Shape (x, y), m_w (w), m_h (h) {} void draw (void) const { cout << "矩形(" << m_x << ',' << m_y << ',' << m_w << ',' << m_h << ')' << endl; } private: int m_w; int m_h; }; class Circle : public Shape { public: Circle (int x, int y, int r) : Shape (x, y), m_r (r) {} void draw (void) const { cout << "圆形(" << m_x << ',' << m_y << ',' << m_r << ')' << endl; } private: int m_r; }; class Triangle : public Shape { public: void foo (void) {} }; void render (Shape* shapes[]) { for (size_t i = 0; shapes[i]; ++i) shapes[i]->draw (); } int main (void) { Shape* shapes[1024] = {}; shapes[0] = new Rect (1, 2, 3, 4); shapes[1] = new Circle (5, 6, 7); shapes[2] = new Circle (8, 9, 10); shapes[3] = new Rect (11, 12, 13, 14); shapes[4] = new Rect (15, 16, 17, 18); render (shapes); // Shape shape (1, 2); // Triangle* pt = new Triangle; return 0; } type.cpp #include <iostream> using namespace std; class A { public: int foo (int x, int y) { // m_data = 10; return x + y; } int m_data; }; class B : public A { public: int m_memb; }; int main (void) { A* p = NULL; cout << p->foo (100, 200) << endl; B b; p = &b; cout << (p->m_data = 100) << endl; A a; B* pb = static_cast<B*> (&a); cout << (pb->m_memb = 200) << endl; return 0; } typeid.cpp #include <iostream> #include <typeinfo> #include <cstring> using namespace std; class XYZ {}; class A { virtual void foo (void) {} }; class B : public A {}; void bar (A* pa) { // if (! strcmp (typeid (*pa).name (), "1A")) if (typeid (*pa) == typeid (A)) cout << "传入的是个A对象" << endl; else // if (! strcmp (typeid (*pa).name (), "1B")) if (typeid (*pa) == typeid (B)) cout << "传入的是个B对象" << endl; else cout << "传入的是个怪物" << endl; } int main (void) { cout << typeid (char).name () << endl; cout << typeid (unsigned char).name () << endl; cout << typeid (short).name () << endl; cout << typeid (unsigned short).name () << endl; cout << typeid (int).name () << endl; cout << typeid (unsigned int).name () << endl; cout << typeid (long).name () << endl; cout << typeid (unsigned long).name () << endl; cout << typeid (long long).name () << endl; cout << typeid (unsigned long long).name () << endl; cout << typeid (float).name () << endl; cout << typeid (double).name () << endl; cout << typeid (long double).name () << endl; cout << typeid (int*****).name () << endl; cout << typeid (const char*).name () << endl; cout << typeid (char const*).name () << endl; cout << typeid (char *const).name () << endl; cout << typeid (float[10]).name () << endl; cout << typeid (float[10][5]).name () << endl; cout << typeid (int* (*) (int*)).name () << endl; cout << typeid (int* (*[10]) (int*)).name () << endl; cout << typeid (XYZ).name () << endl; B b; A* pa = &b; cout << typeid (*pa).name () << endl; A a; bar (&a); bar (&b); return 0; } vdes.cpp #include <iostream> using namespace std; class A { public: A (void) { cout << "A构造" << endl; } virtual ~A (void) { cout << "A析构" << endl; } }; class B : public A { public: B (void) { cout << "B构造" << endl; } ~B (void) { cout << "B析构" << endl; } }; int main (void) { // B* p = new B; A* p = new B; // ... delete p; return 0; }; vtbl.cpp #include <iostream> using namespace std; typedef void (*VFUN) (void*); typedef VFUN* VPTR; class A { public: A (int data) : m_data (data) {} virtual void foo (void) { cout << "A::foo:" << m_data << endl; } virtual void bar (void) { cout << "A::bar:" << m_data << endl; } protected: int m_data; }; class B : public A { public: B (int data) : A (data) {} void foo (void) { cout << "B::foo:" << m_data << endl; } }; int main (void) { A a (100); a.foo (); a.bar (); B b (200); b.foo (); b.bar (); A& r = b; r.foo (); r.bar (); cout << "----------------" << endl; VPTR vptr = *(VPTR*)&a; cout << (void*)vptr[0] << ' ' << (void*)vptr[1] << endl; vptr[0] (&a); vptr[1] (&a); vptr = *(VPTR*)&b; cout << (void*)vptr[0] << ' ' << (void*)vptr[1] << endl; vptr[0] (&b); vptr[1] (&b); return 0; } day09 consex.cpp #include <cstdio> #include <iostream> using namespace std; class A { public: A (size_t size) : m_data (new int[size]) { FILE* fp = fopen ("none", "r"); if (! fp) { cout << "释放内存资源" << endl; delete[] m_data; throw -1; } // ... fclose (fp); } ~A (void) { if (m_data) { cout << "释放内存资源" << endl; delete[] m_data; m_data = NULL; } } private: int* m_data; }; int main (void) { try { A a (1024); // ... } catch (int& ex) { cout << ex << endl; return -1; } return 0; } copy.cpp #include <cstdio> #include <iostream> #include <fstream> using namespace std; int main (int argc, char* argv[]) { if (argc < 3) { cout << "用法:" << argv[0] << " <源文件> <目的文件>" << endl; return -1; } ifstream ifs (argv[1], ios::binary); if (! ifs) { perror ("打开源文件失败"); return -1; } ofstream ofs (argv[2], ios::binary); if (! ofs) { perror ("打开目的文件失败"); return -1; } char buf[1024]; while (ifs.read (buf, 1024)) ofs.write (buf, 1024); if (ifs.eof ()) ofs.write (buf, ifs.gcount ()); else perror ("读取源文件失败"); ofs.close (); ifs.close (); return 0; } except.cpp #include <cstdlib> #include <cstdio> #include <errno.h> #include <cstring> #include <iostream> using namespace std; class CalcException { public: CalcException (string const& msg, string const& file, string const& func, int no) : m_msg (msg), m_file (file), m_func (func), m_no (no) {} friend ostream& operator<< (ostream& os, CalcException const& ex) { return os << ex.m_msg << ":" << ex.m_file << "," << ex.m_func << "," << ex.m_no; } private: string m_msg; string m_file; string m_func; int m_no; }; void foo (void) { // ... cout << "要分配内存..." << endl; void* p = malloc (/*0xFFFFFFFF*/1); if (! p) throw 17; cout << "分配内存成功!" << endl; // ... free (p); FILE* fp = fopen ("none", "r"); if (! fp) throw string (strerror (errno)); // ... fclose (fp); if (0) { throw CalcException ("计算错误", __FILE__, __FUNCTION__, __LINE__); } if (1) throw 3.14; } void bar (void) { cout << "调用foo之前..." << endl; foo (); cout << "调用foo之后..." << endl; } void hum (void) { try { cout << "调用bar之前..." << endl; bar (); cout << "调用bar之后..." << endl; } catch (double& ex) { cout << ex << endl; throw; } } int main (void) { try { cout << "调用hum之前..." << endl; hum (); cout << "调用hum之后..." << endl; } catch (int& ex) { cout << "出错啦:" << ex << endl; return -1; } catch (string& ex) { cout << "失败啦:" << ex << endl; return -1; } catch (CalcException& ex) { cout << ex << endl; return -1; } catch (...) { cout << "其它异常!" << endl; return -1; } return 0; }; format.cpp #include <cmath> #include <iostream> #include <iomanip> #include <fstream> using namespace std; int main (void) { cout << sqrt (200) << endl; cout.precision (10); cout << sqrt (200) << endl; cout.setf (ios::scientific); cout << sqrt (200) << endl; cout << setprecision (8) << sqrt (200) << endl; cout << oct << 127 << endl; cout << hex << 127 << endl; cout << dec << 127 << endl; cout << '[' << setw (10) << 256 << ']' << endl; cout << '[' << setw (10) << left << 256 << ']' << endl; cout << '[' << setfill ('_') << setw (10) << 256 << ']' << endl; cout << '[' << setw (10) << 345 << ']' << '[' << 678 << ']' << endl; ifstream ifs ("i.txt"); ifs.unsetf (ios::skipws); char c; while (ifs >> c) cout << c; cout << endl; ifs.close (); return 0; } seek.cpp #include <iostream> #include <fstream> using namespace std; int main (void) { fstream fs ("seek.txt", ios::in | ios::out); fs << "0123456789"; fs.seekp (-7, ios::cur); cout << "当前位置:" << fs.tellp () << endl; cout << "当前位置:" << fs.tellg () << endl; fs << "ABCD"; fs.seekg (ios::beg); cout << "当前位置:" << fs.tellg () << endl; cout << "当前位置:" << fs.tellp () << endl; // fs.seekg (0, ios::beg); int i; fs >> i; cout << i << endl; // 12 return 0; } stdexcept.cpp #include <errno.h> #include <cstring> #include <cstdio> #include <iostream> #include <stdexcept> using namespace std; class FileException : public exception { public: FileException (void) : m_msg (strerror (errno)) {} const char* what (void) const throw () { return m_msg.c_str (); } ~FileException (void) throw () {} private: string m_msg; }; void foo (void) { char* p = new char[/*0xFFFFFFFF*/1]; FILE* fp = fopen ("none", "r"); if (! fp) { delete[] p; throw FileException (); } // ... fclose (fp); delete[] p; } int main (void) { try { foo (); } catch (bad_alloc& ex) { cout << "处理内存分配失败..." << endl; return -1; } catch (FileException& ex) { cout << "处理文件访问失败..." << endl; return -1; } catch (exception& ex) { cout << "系统错误,请联系系统管理员..." << endl; cout << ex.what () << endl; return -1; } catch (...) { } return 0; } text.cpp #include <cstdio> #include <iostream> #include <fstream> using namespace std; int main (void) { ofstream ofs ("text.txt"); if (! ofs) perror ("打开文件失败"); ofs << 1234 << ' ' << 56.78 << ' ' << "apples" << endl; ofs.close (); ofs.open ("text.txt", ios::app); if (! ofs) perror ("打开文件失败"); ofs << "append_a_line" << endl; ofs.close (); ifstream ifs ("text.txt"); if (! ifs) perror ("打开文件失败"); int i; double d; string s1, s2; ifs >> i >> d >> s1 >> s2; cout << i << endl; cout << d << endl; cout << s1 << endl; cout << s2 << endl; ifs.close (); return 0; } throw.cpp #include <cstdlib> #include <iostream> using namespace std; void foo (int a) throw (float, int,double,string); //void foo (int a) throw (int, double, string) { void foo (int a) throw (int,double,float,string){ //void foo (int a) throw () { //void foo (int a) { if (a == 1) throw 1; else if (a == 2) throw 3.14; else if (a == 3) throw string ("Hello, World !"); else throw 3.14f; } int main (int argc, char* argv[]) { try { foo (atoi (argv[1])); } catch (int& ex) { cout << ex << endl; } catch (double& ex) { cout << ex << endl; } catch (string& ex) { cout << ex << endl; } catch (float& ex) { cout << ex << endl; } catch (...) { cout << "其它异常!" << endl; } return 0; } vtbl.cpp #include <iostream> using namespace std; typedef void (*VFUN) (void*); typedef VFUN* VPTR; class A { public: A (int data) : m_data (data) { cout << "A构造" << endl; VPTR vptr = *(VPTR*)this; cout << vptr << "->" << (void*)vptr[0] << ',' << (void*)vptr[1] << endl; } ~A (void) { cout << "A析构" << endl; VPTR vptr = *(VPTR*)this; cout << vptr << "->" << (void*)vptr[0] << ',' << (void*)vptr[1] << endl; } virtual void foo (void) { cout << "A::foo:" << m_data << endl; } virtual void bar (void) { cout << "A::bar:" << m_data << endl; } protected: int m_data; }; class B : public A { public: B (int data) : A (data) { cout << "B构造" << endl; VPTR vptr = *(VPTR*)this; cout << vptr << "->" << (void*)vptr[0] << ',' << (void*)vptr[1] << endl; } ~B (void) { cout << "B析构" << endl; VPTR vptr = *(VPTR*)this; cout << vptr << "->" << (void*)vptr[0] << ',' << (void*)vptr[1] << endl; } void foo (void) { cout << "B::foo:" << m_data << endl; } }; int main (void) { A a (100); a.foo (); a.bar (); B b (200); b.foo (); b.bar (); A& r = b; r.foo (); r.bar (); cout << "----------------" << endl; VPTR vptr = *(VPTR*)&a; cout << "A之虚表指针:" << vptr << endl; cout << (void*)vptr[0] << ' ' << (void*)vptr[1] << endl; vptr[0] (&a); vptr[1] (&a); vptr = *(VPTR*)&b; cout << "B之虚表指针:" << vptr << endl; cout << (void*)vptr[0] << ' ' << (void*)vptr[1] << endl; vptr[0] (&b); vptr[1] (&b); return 0; } STL day01 array.cpp #include <iostream> using namespace std; template<typename T> class Array { public: T& operator[] (size_t i) { return m_array[i]; } T const& operator[] (size_t i) const { return const_cast<Array<T>&> (*this) [i]; } private: T m_array[3]; }; int main (void) { Array<int> a1; a1[0] = 13; a1[1] = 27; a1[2] = 39; for (size_t i = 0; i < 3; ++i) cout << a1[i] << ' '; cout << endl; Array<double> a2; a2[0] = 1.26; a2[1] = 2.35; a2[2] = 3.14; for (size_t i = 0; i < 3; ++i) cout << a2[i] << ' '; cout << endl; Array<string> a3; a3[0] = "北京"; a3[1] = "上海"; a3[2] = "广州"; for (size_t i = 0; i < 3; ++i) cout << a3[i] << ' '; cout << endl; Array<Array<int> > a4; for (size_t i = 0; i < 3; ++i) for (size_t j = 0; j < 3; ++j) a4[i][j] = (i+1)*10+j+1; // a4.operator[](i).operator[](j) = ..; for (size_t i = 0; i < 3; ++i) { for (size_t j = 0; j < 3; ++j) cout << a4[i][j] << ' '; cout << endl; } Array<Array<Array<int> > > a5; return 0; } ctmpl.cpp #include <iostream> using namespace std; // 类模板 /* template<typename T> class Comparator { public: Comparator (T x, T y) : m_x (x), m_y (y) {} T max (void) const { return m_x < m_y ? m_y : m_x; } T min (void) const { return m_x < m_y ? m_x : m_y; } private: T m_x; T m_y; }; */ template<typename T> class Comparator { public: Comparator (T x, T y); Comparator (Comparator<T> const& that); T max (void) const; T min (void) const; bool equal (void) const; private: T m_x; T m_y; }; template<typename T> Comparator<T>::Comparator (T x, T y) : m_x (x), m_y (y) {} template<typename T> Comparator<T>::Comparator ( Comparator<T> const& that) : m_x (that.m_x), m_y (that.m_y) {} template<typename T> T Comparator<T>::max (void) const { return m_x < m_y ? m_y : m_x; } template<typename T> T Comparator<T>::min (void) const { return m_x < m_y ? m_x : m_y; } template<typename T> bool Comparator<T>::equal (void) const { return m_x == m_y; } class Integer { public: Integer (int data = 0) : m_data (data) {} friend ostream& operator<< (ostream& os, Integer const& integer) { return os << integer.m_data; } bool operator< (Integer const& rhs) const { return m_data < rhs.m_data; } private: int m_data; }; int main (void) { Comparator<int> c1 (123, 456); cout << c1.max () << ' ' << c1.min () << endl; Comparator<double> c2 (1.23, 4.56); cout << c2.max () << ' ' << c2.min () << endl; Comparator<string> c3 ("hello", "world"); cout << c3.max () << ' ' << c3.min () << endl; Comparator<string> c4 = c3; cout << c4.max () << ' ' << c4.min () << endl; Integer i1 (123), i2 (456); Comparator<Integer> c5 (i1, i2); cout << c5.max () << ' ' << c5.min () << endl; // cout << c5.equal () << endl; return 0; } ftmpl.cpp #include <iostream> using namespace std; // 函数模板 template<typename T> T max (T x, T y) { return x < y ? y : x; } int main (void) { // cout << ::max<int> (123, 456) << endl; cout << ::max (123, 456) << endl; // cout << ::max<double> (1.23, 4.56) << endl; cout << ::max (1.23, 4.56) << endl; char s1[] = "hello"; char s2[] = "world"; cout << ::max<string> (s1, s2) << endl; // cout << ::max (s1, s2) << endl; return 0; } ftmpl2.cpp #include <iostream> using namespace std; template<typename T> void foo (void) { T t (100); // A t (100) if (false) cout << t.m_data << endl; cout << t << endl; } class A { public: A (int data) : m_data (data) {} private: int m_data; }; ostream& operator<< (ostream& os, A const& a) { return os << a.m_data; } int main (void) { foo<A> (); // foo<int> (); return 0; } ftmpl3.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename T> void foo (T const& x, T const& y) { cout << "foo:T = " << typeid (T).name () << endl; } template<typename T> void bar (T x, T y) { cout << "bar:T = " << typeid (T).name () << endl; } template<typename T> void hum (int a, int b) { T t; cout << "hum:T = " << typeid (T).name () << endl; } template<typename R, typename T> //template<typename T, typename R> R fun (T const& t) { R r; cout << "fun:R = " << typeid (R).name () << ",T = " << typeid (T).name () << endl; return r; } int main (void) { int a, b; foo (a, b); double c, d; foo (c, d); char e[256], f[256], g[255]; e[10] = 'A'; // *(e+10) = 'A' cout << sizeof (e) << endl; // 256 foo (e, f); // 数组名e和f表示数组整体 bar (e, f); // 数组名e和f表示首元素地址 // foo (e, g); bar (e, g); foo ("hello", "world"); // foo ("hello", "tarena"); bar ("hello", "tarena"); hum<string> (10, 20); int x; // double y = fun<double, int> (x); double y = fun<double> (x); foo (c, (double)a); // 显式转换,隐式推断 foo<double> (c, a); // 显式实例化,隐式转换 return 0; } macro.cpp #include <iostream> using namespace std; #define MAX(T) T max_##T (T x, T y) { return x < y ? y : x; } MAX (int) // int max_int (int x, int y) { ... } MAX (double) // double max_double (...) { ... } MAX (string) // string max_string (...) { ... } #define max(T) max_##T int main (void) { cout << max(int) (123, 456) << endl; // cout << max_int (123, 456) << endl; cout << max(double) (1.23, 4.56) << endl; char s1[] = "hello"; char s2[] = "world"; cout << max(string) (s1, s2) << endl; return 0; } overload.cpp #include <cstring> #include <iostream> #include <typeinfo> using namespace std; template<typename T> T const& max (T const& x, T const& y) { cout << "<1" << typeid (x).name () << '>' << flush; return x < y ? y : x; } char const* const& max (char const* const& x, char const* const& y) { cout << "<2" << typeid (x).name () << '>' << flush; return strcmp (x, y) < 0 ? y : x; } /* char const* max (char const* x, const char* y) { return strcmp (x, y) < 0 ? y : x; } */ template<typename T> T* const& max (T* const& x, T* const& y) { cout << "<3" << typeid (x).name () << '>' << flush; return *x < *y ? y : x; } template<typename T> T const& max (T const& x, T const& y, T const& z) { cout << "<4" << typeid (x).name () << '>' << flush; return ::max (::max (x, y), z); } /* char const* const& max (char const* const& x, char const* const& y) { cout << "<2" << typeid (x).name () << '>' << flush; return strcmp (x, y) < 0 ? y : x; } */ int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max ("hello", "world") << endl; int x = 123, y = 456; cout << *::max (&x, &y) << endl; char const* a = "ABC"; char const* b = "AB"; char const* c = "A"; // 编译器优先选择普通函数 cout << ::max (a, b) << endl; // 2 // 除非函数模板能够产生具有更好匹配性的函数 int d = 100, e = 200; cout << ::max (d, e) << endl; // 1 // 在参数传递过程中如果需要隐式类型转换,编译器 // 只能选择普通函数 cout << ::max (a, (char*)b) << endl; // 2 // 通过模板参数表告知编译器使用函数模板 // 针对指针的版本显然比任意类型版本更加具体 cout << ::max<> (b, a) << endl; // 3 // 显式指定的模板参数必须在所选择的重载版本中与 // 调用参数的类型保持一致 cout << ::max<char const*> (b, a) << endl; // 1 cout << ::max (123, 789, 456) << endl; // 在函数模板的实例化函数中,编译器优先选择普通 // 函数,但是该普通函数必须声明于模板之前 cout << ::max (a, b, c) << endl; char const* const& r = max (a, b, c); cout << r << endl; // ABC char const* g = "123"; char const* h = "12"; char const* i = "1"; max (g, h, i); cout << r << endl; // ABC return 0; } static.cpp #include <iostream> using namespace std; template<typename T> class A { public: static int* addr (void) { return &m_data; } private: static int m_data; }; template<typename T> int A<T>::m_data = 0; int main (void) { A<int> a1, a2; A<double> a3, a4; cout << a1.addr () << ' ' << a2.addr () << endl; cout << a3.addr () << ' ' << a4.addr () << endl; return 0; } typed.cpp #include <iostream> using namespace std; int max_int (int x, int y) { return x < y ? y : x; } double max_double (double x, double y) { return x < y ? y : x; } string max_string (string x, string y) { return x < y ? y : x; } int main (void) { cout << max_int (123, 456) << endl; cout << max_double (1.23, 4.56) << endl; cout << max_string ("hello", "world") << endl; return 0; } untyped.cpp #include <iostream> using namespace std; #define max(x, y) ((x) < (y) ? (y) : (x)) int main (void) { cout << max (123, 456) << endl; cout << max (1.23, 4.56) << endl; char s2[] = "hello"; char s1[] = "world"; cout << max (s2, s1) << endl; return 0; } day02 array.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename T = int, size_t S = 3> class Array { public: T& operator[] (size_t i) { return m_array[i]; } T const& operator[] (size_t i) const { return const_cast<Array<T,S>&> (*this) [i]; } void typeOf (void) const { cout << typeid (m_array).name () << endl; } private: T m_array[S]; }; int square (int x) { return x * x; } template<int x> int square (void) { return x * x; } template<int/*float*//*double*//*string*/ x> void foo (void) { cout << x << endl; } template<char const* x> void bar (void) { cout << x << endl; } char const* g_global = "Hello, World !"; static char g_static[] = "Hello, World !"; char g_extern[] = "Hello, World !"; int main (void) { // Array<int, 5> a1; // Array<int, 2+3> a1; int const /*volatile*/ a = 2, b = 3; Array<int, a+b> a1; a1.typeOf (); Array<string> a2; a2.typeOf (); int x; cin >> x; cout << square (x) << endl; cout << square<13> () << endl; foo<3> (); // bar<"Hello, World !"> (); // bar<g_global> (); // bar<g_static> (); bar<g_extern> (); return 0; } defarg.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename A = long, typename B = A, typename C = string> class D { public: static void print (void) { cout << typeid (A).name () << ' ' << typeid (B).name () << ' ' << typeid (C).name () << endl; } }; template<typename A = long, typename B = A, typename C = string> void print (void) { cout << typeid (A).name () << ' ' << typeid (B).name () << ' ' << typeid (C).name () << endl; } /* void foo (int x, int y = x) { int a = 100, b = a; cout << x << ' ' << y << endl; } */ int main (void) { D<char, short, int>::print (); D<char, short>::print (); D<char>::print (); D<>::print (); cout << "----------------" << endl; print<char, short, int> (); print<char, short> (); print<char> (); print<> (); // foo (100); return 0; } inherit.cpp #include <cstdlib> #include <iostream> using namespace std; template<typename T> class A { public: A (void) : m_data (1234) {} void foo (void) { cout << "A::foo" << endl; } void exit (int status) { cout << "再见!" << endl; } protected: int m_data; }; template<typename T> class B : public A<T> { public: void bar (void) { /* A<T>::foo (); cout << A<T>::m_data << endl; */ this->foo (); cout << this->m_data << endl; this->exit (0); } }; int main (void) { B<int> b; b.bar (); return 0; } init.cpp #include <iostream> using namespace std; template<typename T> void foo (void) { T t = T (); // string t = string (); // int t = int (); cout << '[' << t << ']' << endl; } int main (void) { foo<string> (); foo<int> (); return 0; } part.cpp #include <iostream> #include <typeinfo> using namespace std; // 通用版本 template<typename A, typename B> class C { public: static void print (void) { cout << "C<A,B>" << endl; } }; // 针对B取short类型的局部特化版本 template<typename A> class C<A, short> { public: static void print (void) { cout << "C<A,short>" << endl; } }; // 针对A和B取相同类型的局部特化版本 template<typename A> class C<A, A> { public: static void print (void) { cout << "C<A,A>" << endl; } }; // 针对A和B都取指针的局部特化版本 template<typename A, typename B> class C<A*, B*> { public: static void print (void) { cout << "C<A*,B*>" << endl; } }; // 针对A和B都去同类型指针的局部特化版本 template<typename A> class C<A*, A*> { public: static void print (void) { cout << "C<A*,A*>" << endl; } }; // 针对数组的局部特化版本 template<typename A, typename B> class C<A[], B[]> { public: static void print (void) { cout << "C<A[],B[]>" << endl; } }; template<typename A, typename B> void foo (void) { cout << "通用版本" << endl; } template<> void foo<int, int> (void) { cout << "完全特化" << endl; } /* 函数模板不能局部特化 template<typename A> void foo<A, short> (void) { cout << "局部特化" << endl; } */ int main (void) { C<int, char>::print (); C<int, short>::print (); C<double, short>::print (); C<int, int>::print (); C<double, double>::print (); // C<short, short>::print (); C<int*, char*>::print (); C<int*, int*>::print (); C<int[], char[]>::print (); foo<char, short> (); foo<int, int> (); return 0; } spec.cpp #include <cstring> #include <iostream> using namespace std; // 通用版本 template<typename T> T max (T x, T y) { return x < y ? y : x; } // 针对char const*类型的重载版本 char const* max (char const* x, char const* y) { return strcmp (x, y) < 0 ? y : x; } // 通用版本 template<typename T> class Comparator { public: Comparator (T x, T y) : m_x (x), m_y (y) {} T max (void) const { return m_x < m_y ? m_y : m_x; } private: T m_x; T m_y; }; // 针对char const*类型的特化版本 /* template<> class Comparator<char const*> { public: static char const* zuidazhi (char const*x, char const* y) { return strcmp (x, y) < 0 ? y : x; } }; */ // 针对char const*类型的成员特化版本 template<> char const* Comparator<char const*>::max ( void) const { return strcmp (m_x, m_y) < 0 ? m_y : m_x; } int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max ("hello", "world") << endl; cout << "----------------" << endl; cout << Comparator<int> (123, 456).max () << endl; cout << Comparator<double> (1.23, 4.56).max () << endl; cout << Comparator<string> ("hello", "world").max () << endl; /* cout << Comparator<char const*>::zuidazhi ( "hello", "world") << endl; */ cout << Comparator<char const*> ("hello", "world").max () << endl; return 0; } template.cpp #include <iostream> #include <typeinfo> using namespace std; class A { public: template<typename T> void foo (void) { T t; cout << typeid (t).name () << endl; } void bar (void) { cout << "bar函数" << endl; } }; template<typename T> void bar (void) { T a, *p = &a; a.template foo<int> (); a.bar (); p->template foo<double> (); p->bar (); } int main (void) { A a; a.foo<int> (); a.foo<double> (); bar<A> (); return 0; } tmplarg.cpp #include <iostream> using namespace std; template<typename T> class A { public: A (T const& t) : m_t (t) {} void print (void) const { cout <<"A:" << m_t << endl; } private: T m_t; }; template<typename T> class C { public: C (T const& t) : m_t (t) {} void print (void) const { cout << "C:" << m_t << endl; } private: T m_t; }; template<typename T, template<typename> class D> class B { public: B (T const& t) : m_d (t) {} // A<T> m_a; // C<T> m_c; D<T> m_d; }; int main (void) { B<int, A> b1 (1234); b1.m_d.print (); B<string, C> b2 ("达内科技"); b2.m_d.print (); return 0; } tmplarg2.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename A, typename B> class C { public: static void print (void) { cout << "C:" << typeid (A).name () << ' ' << typeid (B).name () << endl; } }; template<typename A, typename B> class D { public: static void print (void) { cout << "D:" << typeid (A).name () << ' ' << typeid (B).name () << endl; } }; template<typename A, typename B, template<typename, typename> class Y> class X : public Y<A, B> {}; int main (void) { X<int, double, C>::print (); X<short, string, D>::print (); return 0; } typename.cpp #include <iostream> using namespace std; class A { public: typedef unsigned int UINT; typedef struct Student { char name[128]; int age; } STUDENT; class B {}; }; template</*typename*/class T> void foo (void) { typename T::UINT x; typename T::STUDENT y = {"张飞", 25}; typename T::B z; } int main (void) { A::UINT x; A::STUDENT y = {"张飞", 25}; A::B z; foo<A> (); return 0; } virtual.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename T> class A { public: /* template<typename B> void foo (B const& b) { cout << typeid (*this).name () << ' ' << typeid (b).name () << endl; } */ template<typename B> void foo (B const& b); virtual void bar (void) { cout << "A::bar" << endl; } /* template<typename D> virtual void hum (void) { cout << "A::hum" << endl; } */ }; template<typename T> template<typename B> void A<T>::foo (B const& b) { cout << typeid (*this).name () << ' ' << typeid (b).name () << endl; } template<typename T> class C : public A<T> { private: void bar (void) { cout << "C::bar" << endl; } }; int main (void) { A<int> a; double d; a.foo (d); C<double> c; A<double>& r = c; r.bar (); return 0; } /error max.h #ifndef _MAX_H #define _MAX_H template<typename T> T max (T x, T y); template<typename T> class Comparator { public: Comparator (T x, T y); T max (void) const; private: T m_x, m_y; }; #endif // _MAX_H max.cpp #include <cstring> #include "max.h" template<typename T> T max (T x, T y) { return x < y ? y : x; } char const* max (char const* x, char const* y) { return strcmp (x, y) < 0 ? y : x; } template<typename T> Comparator<T>::Comparator (T x, T y) : m_x (x), m_y (y) {} template<typename T> T Comparator<T>::max (void) const { return m_x < m_y ? m_y : m_x; } template<> char const* Comparator<char const*>::max ( void) const { return strcmp (m_x, m_y) < 0 ? m_y : m_x; } main.cpp #include <iostream> using namespace std; #include "max.h" int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max<char const*> ("hello", "world") << endl; cout << "----------------" << endl; cout << Comparator<int> (123, 456).max () << endl; cout << Comparator<double> (1.23, 4.56).max () << endl; cout << Comparator<string> ("hello", "world").max () << endl; cout << Comparator<char const*> ("hello", "world").max () << endl; return 0; } /export max.h #ifndef _MAX_H #define _MAX_H export template<typename T> T max (T x, T y); export template<typename T> class Comparator { public: Comparator (T x, T y); T max (void) const; private: T m_x, m_y; }; #endif // _MAX_H max.cpp #include <cstring> #include "max.h" template<typename T> T max (T x, T y) { return x < y ? y : x; } char const* max (char const* x, char const* y) { return strcmp (x, y) < 0 ? y : x; } template<typename T> Comparator<T>::Comparator (T x, T y) : m_x (x), m_y (y) {} template<typename T> T Comparator<T>::max (void) const { return m_x < m_y ? m_y : m_x; } template<> char const* Comparator<char const*>::max ( void) const { return strcmp (m_x, m_y) < 0 ? m_y : m_x; } main.cpp #include <iostream> using namespace std; #include "max.h" int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max<char const*> ("hello", "world") << endl; cout << "----------------" << endl; cout << Comparator<int> (123, 456).max () << endl; cout << Comparator<double> (1.23, 4.56).max () << endl; cout << Comparator<string> ("hello", "world").max () << endl; cout << Comparator<char const*> ("hello", "world").max () << endl; return 0; } /include max.h #ifndef _MAX_H #define _MAX_H template<typename T> T max (T x, T y); template<typename T> class Comparator { public: Comparator (T x, T y); T max (void) const; private: T m_x, m_y; }; #include "max.cpp" #endif // _MAX_H max.cpp #include <cstring> template<typename T> T max (T x, T y) { return x < y ? y : x; } char const* max (char const* x, char const* y) { return strcmp (x, y) < 0 ? y : x; } template<typename T> Comparator<T>::Comparator (T x, T y) : m_x (x), m_y (y) {} template<typename T> T Comparator<T>::max (void) const { return m_x < m_y ? m_y : m_x; } template<> char const* Comparator<char const*>::max ( void) const { return strcmp (m_x, m_y) < 0 ? m_y : m_x; } main.cpp #include <iostream> using namespace std; #include "max.h" int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max ("hello", "world") << endl; cout << "----------------" << endl; cout << Comparator<int> (123, 456).max () << endl; cout << Comparator<double> (1.23, 4.56).max () << endl; cout << Comparator<string> ("hello", "world").max () << endl; cout << Comparator<char const*> ("hello", "world").max () << endl; return 0; } /inst max.h #ifndef _MAX_H #define _MAX_H template<typename T> T max (T x, T y); char const* max (char const*, char const*); template<typename T> class Comparator { public: Comparator (T x, T y); T max (void) const; private: T m_x, m_y; }; #endif // _MAX_H max.cpp #include <cstring> #include <string> using namespace std; #include "max.h" template<typename T> T max (T x, T y) { return x < y ? y : x; } char const* max (char const* x, char const* y) { return strcmp (x, y) < 0 ? y : x; } template<typename T> Comparator<T>::Comparator (T x, T y) : m_x (x), m_y (y) {} template<typename T> T Comparator<T>::max (void) const { return m_x < m_y ? m_y : m_x; } template<> char const* Comparator<char const*>::max ( void) const { return strcmp (m_x, m_y) < 0 ? m_y : m_x; } // 显式实例化 template int max<int> (int, int); template double max<double> (double, double); template string max<string> (string, string); template class Comparator<int>; template class Comparator<double>; template class Comparator<string>; template class Comparator<char const*>; main.cpp #include <iostream> using namespace std; #include "max.h" int main (void) { cout << ::max (123, 456) << endl; cout << ::max (1.23, 4.56) << endl; cout << ::max<string> ("hello", "world") << endl; cout << ::max ("hello", "world") << endl; cout << "----------------" << endl; cout << Comparator<int> (123, 456).max () << endl; cout << Comparator<double> (1.23, 4.56).max () << endl; cout << Comparator<string> ("hello", "world").max () << endl; cout << Comparator<char const*> ("hello", "world").max () << endl; return 0; } day03 defarg.cpp #include <iostream> #include <typeinfo> using namespace std; template<typename T = int> void foo (T t) { cout << typeid (t).name () << endl; } int main (void) { foo (1.23); // 隐式推断优先 return 0; } list.cpp // 双向线性链表容器 #include <cstring> #include <iostream> #include <stdexcept> using namespace std; template<typename T> class List { public: // 构造、析构、拷贝构造、拷贝赋值 List (void) : m_head (NULL), m_tail (NULL) {} ~List (void) { clear (); } List (List const& that) : m_head (NULL), m_tail (NULL) { for (Node* node = that.m_head; node; node = node->m_next) push_back (node->m_data); } List& operator= (List const& rhs) { if (&rhs != this) { List list = rhs; swap (m_head, list.m_head); swap (m_tail, list.m_tail); } return *this; } // 获取首元素 T& front (void) { if (empty ()) throw underflow_error ("链表下溢!"); return m_head->m_data; } T const& front (void) const { return const_cast<List*> (this)->front (); } // 向首部压入 void push_front (T const& data) { m_head = new Node (data, NULL, m_head); if (m_head->m_next) m_head->m_next->m_prev = m_head; else m_tail = m_head; } // 从首部弹出 void pop_front (void) { if (empty ()) throw underflow_error ("链表下溢!"); Node* next = m_head->m_next; delete m_head; m_head = next; if (m_head) m_head->m_prev = NULL; else m_tail = NULL; } // 获取尾元素 T& back (void) { if (empty ()) throw underflow_error ("链表下溢!"); return m_tail->m_data; } T const& back (void) const { return const_cast<List*> (this)->back (); } // 向尾部压入 void push_back (T const& data) { m_tail = new Node (data, m_tail); if (m_tail->m_prev) m_tail->m_prev->m_next = m_tail; else m_head = m_tail; } // 从尾部弹出 void pop_back (void) { if (empty ()) throw underflow_error ("链表下溢!"); Node* prev = m_tail->m_prev; delete m_tail; m_tail = prev; if (m_tail) m_tail->m_next = NULL; else m_head = NULL; } // 删除所有匹配元素 void remove (T const& data) { for (Node* node = m_head, *next; node; node = next) { next = node->m_next; if (equal (node->m_data, data)) { if (node->m_prev) node->m_prev->m_next = node->m_next; else m_head = node->m_next; if (node->m_next) node->m_next->m_prev = node->m_prev; else m_tail = node->m_prev; delete node; } } } // 清空 void clear (void) { for (Node* next; m_head; m_head = next) { next = m_head->m_next; delete m_head; } m_tail = NULL; } // 判空 bool empty (void) const { return ! m_head && ! m_tail; } // 大小 size_t size (void) const { size_t nodes = 0; for (Node* node = m_head; node; node = node->m_next) ++nodes; return nodes; } // SHIT ! T& operator[] (size_t i) { for (Node* node = m_head; node; node = node->m_next) if (i-- == 0) return node->m_data; throw out_of_range ("链表越界!"); } // 输出 friend ostream& operator<< (ostream& os, List const& list) { for (Node* node = list.m_head; node; node = node->m_next) os << *node; return os; } private: // 节点 class Node { public: Node (T const& data, Node* prev = NULL, Node* next = NULL) : m_data (data), m_prev (prev), m_next (next) {} friend ostream& operator<< (ostream& os, Node const& node) { return os << '(' << node.m_data << ')'; } T m_data; // 数据 Node* m_prev; // 前指针 Node* m_next; // 后指针 }; // 通用版本 bool equal (T const& x, T const& y) const { return x == y; } Node* m_head; // 头指针 Node* m_tail; // 尾指针 public: // 正向迭代器 class Iterator { public: Iterator (Node* head = NULL, Node* tail = NULL, Node* node = NULL) : m_head (head), m_tail (tail), m_node (node) {} bool operator== (Iterator const& it) const { return m_node == it.m_node; } bool operator!= (Iterator const& it) const { return ! (*this == it); } Iterator& operator++ (void) { if (m_node) m_node = m_node->m_next; else m_node = m_head; return *this; } Iterator const operator++ (int) { Iterator old = *this; ++*this; return old; } Iterator& operator-- (void) { if (m_node) m_node = m_node->m_prev; else m_node = m_tail; return *this; } Iterator const operator-- (int) { Iterator old = *this; --*this; return old; } T& operator* (void) const { return m_node->m_data; } T* operator-> (void) const { return &**this; } private: Node* m_head; Node* m_tail; Node* m_node; friend class List; }; // 获取起始正向迭代器 Iterator begin (void) { return Iterator (m_head, m_tail, m_head); } // 获取终止正向迭代器 Iterator end (void) { return Iterator (m_head, m_tail); } // 插入 Iterator insert (Iterator loc, T const& data) { if (loc == end ()) { push_back (data); return Iterator (m_head, m_tail, m_tail); } else { Node* node = new Node (data, loc.m_node->m_prev, loc.m_node); if (node->m_prev) node->m_prev->m_next = node; else m_head = node; node->m_next->m_prev = node; return Iterator (m_head, m_tail, node); } } // 删除 Iterator erase (Iterator loc) { if (loc == end ()) throw invalid_argument ("无效参数!"); if (loc.m_node->m_prev) loc.m_node->m_prev->m_next = loc.m_node->m_next; else m_head = loc.m_node->m_next; if (loc.m_node->m_next) loc.m_node->m_next->m_prev = loc.m_node->m_prev; else m_tail = loc.m_node->m_prev; Node* next = loc.m_node->m_next; delete loc.m_node; return Iterator (m_head, m_tail, next); } // 常正向迭代器 // 反向迭代器 // 常反向迭代器 }; // 针对char const*类型的特化版本 template<> bool List<char const*>::equal (char const* const& x, char const* const& y) const { return ! strcmp (x, y); } // 线性查找 template<typename IT, typename T> IT find (IT begin, IT end, T const& key) { IT it; for (it = begin; it != end; ++it) if (*it == key) break; return it; } // 测试用例 void test1 (void) { List<int> l1; l1.push_front (30); l1.push_front (20); l1.push_front (10); cout << l1 << endl; // 10 20 30 l1.pop_front (); cout << l1 << endl; // 20 30 l1.front () += 5; cout << l1 << endl; // 25 30 List<int> const& cr = l1; cout << cr.front () << endl; // cr.front () = 20; l1.push_back (40); l1.push_back (50); l1.push_back (60); cout << l1 << endl; // 25 30 40 50 60 l1.pop_back (); cout << l1 << endl; // 25 30 40 50 --l1.back (); cout << l1 << endl; // 25 30 40 49 List<int> const* cp = &l1; cout << cp->back () << endl; // cp->back ()++; l1.push_front (40); l1.push_back (40); l1.push_back (40); cout << l1 << endl; // 40 25 30 40 49 40 40 l1.remove (40); cout << l1 << endl; // 25 30 49 cout << l1.size () << endl; // 3 cout << boolalpha << l1.empty () << endl; // false l1.clear (); cout << l1.size () << endl; // 0 cout << l1.empty () << endl; // true l1.push_back (100); l1.push_back (200); l1.push_back (300); List<int> l2 = l1; // 拷贝构造 cout << "l1:" << l1 << endl; // 100 200 300 cout << "l2:" << l2 << endl; // 100 200 300 l1.pop_front (); ++l2.back (); cout << "l1:" << l1 << endl; // 200 300 cout << "l2:" << l2 << endl; // 100 200 301 l2 = l1; // 拷贝赋值 cout << "l1:" << l1 << endl; // 200 300 cout << "l2:" << l2 << endl; // 200 300 l1.push_front (100); l2.back () = 400; cout << "l1:" << l1 << endl; // 100 200 300 cout << "l2:" << l2 << endl; // 200 400 } void test2 (void) { char sa[][256] = { "北京", "天津", "上海", "天津", "北京", "天津"}; List<string> l1; for (size_t i = 0; i < 6; ++i) l1.push_back (sa[i]); cout << l1 << endl; l1.remove ("天津"); cout << l1 << endl; List<char const*> l2; for (size_t i = 0; i < 6; ++i) l2.push_back (sa[i]); cout << l2 << endl; l2.remove ("天津"); cout << l2 << endl; } void test3 (void) { List<int> l1; l1.push_back (13); l1.push_back (26); l1.push_back (19); l1.push_back (26); l1.push_back (37); cout << l1 << endl; /* size_t size = l1.size (); for (size_t i = 0; i < size; ++i) ++l1[i]; */ for (List<int>::Iterator it = l1.begin (); it != l1.end (); ++it) ++*it; cout << l1 << endl; } void test4 (void) { List<int> l1; l1.insert ( l1.insert ( l1.insert ( l1.insert ( l1.insert (l1.end (), 50), 40), 30), 20), 10); cout << l1 << endl; // 10 20 30 40 50 List<int>::Iterator loc = l1.begin (); l1.insert (++++loc, 25); cout << l1 << endl; l1.insert (l1.begin (), 5); cout << l1 << endl; l1.insert (l1.end (), 55); cout << l1 << endl; loc = l1.end (); l1.erase (l1.erase (l1.erase (--------loc))); cout << l1 << endl; } void test5 (void) { int ai[] = {17, 23, 44, 19, 23}; int* p = find (ai, ai + 5, /*45*/44); if (p == ai + 5) cout << "没找到!" << endl; else cout << "找到了:" << *p << endl; List<string> ls; ls.push_back ("张飞"); ls.push_back ("赵云"); ls.push_back ("关羽"); ls.push_back ("刘备"); ls.push_back ("曹操"); List<string>::Iterator it = find (ls.begin (), ls.end (), "刘备"/*"黄忠"*/); if (it == ls.end ()) cout << "没找到!" << endl; else cout << "找到了:" << *it << endl; } int main (void) { // test1 (); // test2 (); // test3 (); // test4 (); test5 (); return 0; } nontype.cpp #include <iostream> using namespace std; int square (int x) { return x * x; } template<int x> int square2 (void) { return x * x; } int main (void) { cout << square (13) << endl; cout << square (14) << endl; cout << square2<13> () << endl; cout << square2<14> () << endl; return 0; } poly.cpp #include <iostream> using namespace std; int add (int x, int y) { return x + y; } int sub (int x, int y) { return x - y; } int mul (int x, int y) { return x * y; } int div (int x, int y) { return x / y; } // 基于函数指针的多态函数 int cal (int x, int y, int (*pfunc) (int, int)) { return pfunc (x, y); } class Cal { public: virtual int cal (int x, int y) const = 0; }; class Add : public Cal { public: int cal (int x, int y) const { return x + y; } }; class Sub : public Cal { public: int cal (int x, int y) const { return x - y; } }; class Mul : public Cal { public: int cal (int x, int y) const { return x * y; } }; class Div : public Cal { public: int cal (int x, int y) const { return x / y; } }; // 基于虚函数的多态函数 int cal (int x, int y, Cal const& c) { return c.cal (x, y); } class A { public: static int cal (int x, int y) { return x + y; } }; class S { public: static int cal (int x, int y) { return x - y; } }; class M { public: static int cal (int x, int y) { return x * y; } }; class D { public: static int cal (int x, int y) { return x / y; } }; // 基于模板的多态函数 template<typename T> int cal (int x, int y) { return T::cal (x, y); } int main (void) { cout << cal (200, 100, add) << endl; cout << cal (200, 100, sub) << endl; cout << cal (200, 100, mul) << endl; cout << cal (200, 100, div) << endl; cout << "--------" << endl; cout << cal (200, 100, Add ()) << endl; cout << cal (200, 100, Sub ()) << endl; cout << cal (200, 100, Mul ()) << endl; cout << cal (200, 100, Div ()) << endl; cout << "--------" << endl; cout << cal<A> (200, 100) << endl; cout << cal<S> (200, 100) << endl; cout << cal<M> (200, 100) << endl; cout << cal<D> (200, 100) << endl; return 0; } virtual.cpp #include <iostream> using namespace std; class A { public: template<int x> virtual int square (void) const { return x * x; } }; int main (void) { A a; cout << a.square<13> () << endl; cout << a.square<14> () << endl; return 0; }; day04 deque.cpp #include <deque> #include "print.h" int main (void) { deque<int> di; di.push_front (30); di.push_front (20); di.push_front (10); print (di.begin (), di.end ()); // 10 20 30 di.pop_front (); print (di.begin (), di.end ()); // 20 30 di.push_back (40); di.push_back (50); di.push_back (60); print (di.begin (), di.end ()); // 20 30 40 50 60 di.pop_back (); print (di.begin (), di.end ()); // 20 30 40 50 di[1] += 5; *(di.begin () + 2) -= 3; print (di.begin (), di.end ()); // 20 35 37 50 // cout << di.capacity () << endl; cout << di.size () << endl; return 0; } list.cpp #include <list> #include <algorithm> #include "print.h" int main (void) { list<int> l1; l1.push_back (10); l1.push_back (20); l1.push_back (20); l1.push_back (20); l1.push_back (10); l1.push_back (30); l1.push_back (30); l1.push_back (20); l1.push_back (30); l1.push_back (30); print (l1.begin (), l1.end ()); l1.sort (); print (l1.begin (), l1.end ()); l1.unique (); print (l1.begin (), l1.end ()); // 10 20 30 list<int> l2; l2.push_back (10000); l2.push_back (20000); l2.push_back (30000); l2.push_back (40000); list<int>::iterator pos = l1.begin (); ++pos; /* l1.splice (pos, l2); *//* list<int>::iterator del = l2.end (); ----del; l1.splice (pos, l2, del); */ list<int>::iterator begin = l2.begin (); ++begin; list<int>::iterator end = l2.end (); --end; l1.splice (pos, l2, begin, end); cout << "l1:" << flush; print (l1.begin (), l1.end ()); cout << "l2:" << flush; print (l2.begin (), l2.end ()); list<int> l3; l3.push_back (16); l3.push_back (22); l3.push_back (28); l3.push_back (43); l3.push_back (57); list<int> l4; l4.push_back (25); l4.push_back (33); l4.push_back (51); l3.merge (l4); // O(N) cout << "l3:" << flush; print (l3.begin (), l3.end ()); cout << "l4:" << flush; print (l4.begin (), l4.end ()); return 0; } map.cpp #include <iostream> #include <map> using namespace std; int main (void) { map<string, int> msi; msi.insert (pair<string, int> ("张飞", 10000)); msi.insert (make_pair ("赵云", 20000)); msi["关羽"] = 30000; typedef map<string, int>::iterator IT; IT it = msi.find ("赵云"); // O(logN) cout << it->first << ":" << it->second << endl; cout << msi["赵云"] << endl; // msi["张飞"] = 40000; pair<IT, bool> res = msi.insert (pair<string, int> ("张飞2", 40000)); if (! res.second) cout << "插入失败!" << endl; else cout << "插入成功:" << res.first->first << ',' << res.first->second << endl; for (IT it = msi.begin (); it != msi.end (); ++it) cout << it->first << ":" << it->second << endl; return 0; } mmap.cpp #include <iostream> #include <map> using namespace std; int main (void) { multimap<string, int> msi; msi.insert (pair<string, int> ("张飞", 10000)); msi.insert (make_pair ("赵云", 20000)); typedef multimap<string, int>::iterator IT; msi.insert (pair<string, int> ("张飞", 40000)); for (IT it = msi.begin (); it != msi.end (); ++it) cout << it->first << ":" << it->second << endl; IT l = msi.lower_bound ("赵云"); cout << l->first << "," << l->second << endl; IT u = msi.upper_bound ("赵云"); // cout << u->first << "," << u->second << endl; for (IT it = l; it != u; ++it) cout << it->first << "," << it->second << endl; return 0; } mset.cpp #include <iostream> #include <set> using namespace std; int main (void) { multiset<int> si; si.insert (10); si.insert (20); si.insert (10); si.insert (30); si.insert (20); si.insert (40); for (multiset<int>::iterator it = si.begin (); it != si.end (); ++it) cout << *it << ' '; cout << endl; return 0; } print.h #include <iostream> using namespace std; template<typename iterator> void print (iterator begin, iterator end) { while (begin != end) cout << *begin++ << ' '; cout << endl; } set.cpp #include <iostream> #include <set> using namespace std; int main (void) { set<int> si; si.insert (10); si.insert (20); si.insert (10); // 失败 si.insert (30); si.insert (20); // 失败 si.insert (40); for (set<int>::iterator it = si.begin (); it != si.end (); ++it) cout << *it << ' '; cout << endl; return 0; } sq.cpp #include <iostream> #include <stack> #include <queue> #include <vector> #include <list> using namespace std; class CmpInt { public: bool operator() (int a, int b) const { return a > b; } }; int main (void) { // stack<string, /*vector*/list<string> > ss; stack<string> ss; ss.push ("C++"); ss.push ("喜欢"); ss.push ("我们"); while (! ss.empty ()) { cout << ss.top () << flush; ss.pop (); } cout << endl; // queue<string, list<string> > qs; queue<string> qs; qs.push ("我们"); qs.push ("讨厌"); qs.push ("Java"); while (! qs.empty ()) { cout << qs.front () << flush; qs.pop (); } cout << endl; // priority_queue<int, vector<int> > pi; priority_queue<int, vector<int>, CmpInt> pi; pi.push (26); pi.push (19); pi.push (37); pi.push (11); pi.push (88); while (! pi.empty ()) { cout << pi.top () << ' ' << flush; pi.pop (); } cout << endl; return 0; } vector1.cpp #include <iostream> #include <vector> using namespace std; void print (vector<int> const& vi) { size_t size = vi.size (); cout << "大小:" << size << endl; cout << "内容:" << flush; for (size_t i = 0; i < size; ++i) cout << vi[i] << ' '; // *(p+i), O(1) cout << endl; } void show (vector<int> const& vi) { cout << "迭代:" << flush; for (vector<int>::const_iterator it = vi.begin (); it != vi.end (); ++it) cout << *it << ' '; cout << endl; } void rshow (vector<int> const& vi) { cout << "反向:" << flush; for (vector<int>::const_reverse_iterator it = vi.rbegin (); it != vi.rend (); ++it) cout << *it << ' '; cout << endl; } int main (void) { vector<int> v1; print (v1); vector<int> v2 (5); print (v2); vector<int> v3 (5, 13); print (v3); int a[] = {10, 20, 30, 40, 50}; // vector<int> v4 (a, a + 5); vector<int> v4 (&a[0], &a[5]); print (v4); show (v4); rshow (v4); ++v4[2]; show (v4); ++*(v4.begin () + 2); show (v4); vector<int>::iterator it = v4.begin (); // ++++it; it += 2; ++*it; show (v4); vector<int>::iterator it2 = v4.begin (); cout << boolalpha << (it > it2) << endl; cout << it - it2 << endl; // cout << it + it2 << endl; vector<int>::reverse_iterator it3 = v4.rbegin (), it4 = it3; it4 += 2; cout << *it4 << ' ' << *it3 << endl; cout << (it3 > it4) << endl; cout << it3 - it4 << endl; vector<int> const* cp = &v4; vector<int>::const_iterator cit = cp->begin (); cout << *cit << endl; // *cit = 100; it = v4.begin (); cout << *it << endl; // 10 v4.push_back (60); it = v4.begin (); cout << *it << endl; // 10 show (v4); return 0; } vector2.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; void show (vector<int> const& vi) { for (vector<int>::const_iterator it = vi.begin (); it != vi.end (); ++it) cout << *it << ' '; cout << endl; } bool cmpint (int a, int b) { return a > b; } class CmpInt { public: bool operator() (int a, int b) const { return a > b; } }; class Student { public: Student (string const& name, int age) : m_name (name), m_age (age) {} bool operator< (Student const& rhs) const { // return m_name < rhs.m_name; return m_age < rhs.m_age; } friend ostream& operator<< (ostream& os, Student const& student) { return os << student.m_name << ',' << student.m_age; } private: string m_name; int m_age; friend class OrderByName; friend class OrderByAge; friend class OrderByNameAndAge; }; class OrderByName { public: bool operator() (Student const& a, Student const& b) const { return a.m_name < b.m_name; } }; class OrderByAge { public: bool operator() (Student const& a, Student const& b) const { return a.m_age < b.m_age; } }; class OrderByNameAndAge { public: bool operator() (Student const& a, Student const& b) const { if (a.m_name == b.m_name) return a.m_age > b.m_age; return a.m_name < b.m_name; } }; int main (void) { vector<int> vi; vi.push_back (10); vi.push_back (20); vi.push_back (30); vi.push_back (20); vi.push_back (50); show (vi); /* // 将向量中的第二个20改成40 vector<int>::iterator it = find (vi.begin (), vi.end (), 20); it = find (it+1, vi.end (), 20); *it = 40; */ // 将向量中所有的20都改成40 for (vector<int>::iterator begin = vi.begin (); begin != vi.end (); ++begin) { vector<int>::iterator it = find (begin, vi.end (), 20); if (it == vi.end ()) break; *it = 40; begin = it; } show (vi); vector<int> v2; v2.push_back (50); v2.push_back (40); v2.push_back (30); v2.push_back (20); v2.push_back (10); show (v2); sort (v2.begin () + 1, v2.end () - 1); show (v2); sort (v2.begin (), v2.end ()); show (v2); // sort (v2.rbegin (), v2.rend ()); // sort (v2.begin (), v2.end (), cmpint); sort (v2.begin (), v2.end (), CmpInt ()); show (v2); vector<Student> vs; vs.push_back (Student ("zhangfei", 25)); vs.push_back (Student ("zhaoyun", 22)); vs.push_back (Student ("zhangfei", 20)); vs.push_back (Student ("zhaoyun", 28)); vs.push_back (Student ("guanyu", 60)); // sort (vs.begin (), vs.end (), OrderByName ()); // sort (vs.begin (), vs.end (), OrderByAge ()); sort (vs.begin (), vs.end (), OrderByNameAndAge ()); for (vector<Student>::iterator it = vs.begin (); it != vs.end (); ++it) cout << *it << endl; return 0; } vector3.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; class A { public: A (void) : m_data (0) { cout << "缺省构造:" << this << endl; } A (int data) : m_data (data) { cout << "有参构造:" << this << endl; } ~A (void) { cout << "析构函数:" << this << endl; } A (A const& that) : m_data (that.m_data) { cout << "拷贝构造:" << &that << "->" << this << endl; } A& operator= (A const& rhs) { m_data = rhs.m_data; cout << "拷贝赋值:" << &rhs << "->" << this << endl; } /* bool operator< (A const& rhs) const { return m_data < rhs.m_data; } */ bool operator== (A const& rhs) const { return m_data == rhs.m_data; } friend ostream& operator<< (ostream& os, A const& a) { return os << a.m_data; } private: int m_data; friend class CmpA; }; class CmpA { public: bool operator() (A const& x, A const& y) const { return x.m_data < y.m_data; } }; int main (void) { cout << "-------- 1 --------" << endl; // vector<A> v1 (3); vector<A> v1 (3, 10); cout << "-------- 2 --------" << endl; v1.push_back (10); cout << "-------- 3 --------" << endl; v1.erase (v1.begin ()); cout << "-------- 4 --------" << endl; v1[0] = 17; v1[1] = 15; v1[2] = 29; // sort (v1.begin (), v1.end ()); sort (v1.begin (), v1.end (), CmpA ()); for (vector<A>::iterator it = v1.begin (); it != v1.end (); ++it) cout << *it << ' '; cout << endl; vector<A>::iterator it = find ( v1.begin (), v1.end (), 17); if (it == v1.end ()) cout << "没找到!" << endl; else cout << "找到了:" << *it << endl; cout << "-------- X --------" << endl; return 0; } vector4.cpp #include <iostream> #include <vector> using namespace std; void print (vector<int> const& vi) { cout << "大小:" << vi.size () << endl; cout << "容量:" << vi.capacity () << endl; cout << "元素:" << flush; for (vector<int>::const_iterator it = vi.begin (); it != vi.end (); ++it) cout << *it << ' '; cout << endl; } int main (void) { vector<int> vi; print (vi); vi.push_back (10); print (vi); vi.push_back (20); print (vi); vi.push_back (30); print (vi); vi.push_back (40); print (vi); vi.push_back (50); print (vi); vi.pop_back (); print (vi); vi.clear (); print (vi); vi.reserve (0); print (vi); vi.reserve (100); print (vi); vi.reserve (10); print (vi); return 0; }