异常

一、try、catch、throw 可以使用 throw 语句在代码块中的任何地方抛出异常。throw 语句的操作数可以是任意的表达式,表达式的结果的类型决定了抛出的异常的类型 C++ 异常机制是跨函数的,且是必须处理的。如果中间函数没有处理就一直抛到最顶层,如果 main 函数也不处理,程序就会挂掉 int main( ) { try{ throw "exception"; }catch(const char * e){ cout << e << endl; }catch(...){ // 捕获所有异常 cout << "..." << endl; } { cout << "finally" << endl; } return 0; } 输出: Start exception finally 0 Finish 二、std::exception class exception { public: exception() throw(); exception(const exception& rhs) throw(); exception& operator=(const exception& rhs) throw(); virtual ~exception() throw(); virtual const char *what() const throw(); }; 派生了两个异常类:...

January 15, 2022 · 1 min · Rick Cui

类型转换

1. static_cast<> 可以转换内置数据类型; 不可以转换没有关系的指针或引用; 可以转换有继承关系的指针或引用(父类转子类或子类转父类都可以); // static_cast<> // 1. 内置对象 int a = 97; char c = static_cast<char>(a); // OK cout << c << endl; // 2. 自定义类型对象 // Building bb; // Animal aa = static_cast<Animal>(bb); // error: no matching function for call to ‘Animal::Animal(Building&)’ // 3. 不同类型的指针转换 // int *p = &a; // char *pc = static_cast<char*>(p); // error: invalid static_cast from type ‘int*’ to type ‘char*’ // cout << pc << endl; // Animal * pa = NULL; // Building *pb = static_cast<Building*>(pa); // error: invalid static_cast from type ‘Animal*’ to type ‘Building*’ // 4....

January 15, 2022 · 2 min · Rick Cui

自定义数组实现

要求 可以对内置数据类型以及自定义数据类型的数据进行存储 将数组中的数据存储到堆区 构造函数中可以传入数组的容量 提供对应的拷贝构造函数以及 operator= 防止浅拷贝问题 提供尾插法和尾删法对数组中的数据进行增加和删除 可以通过下标的方式访问数组中的元素 可以获取数组中当前元素个数和数组的容量 实现 template<class T> class MyArray{ public: MyArray(int capacity){ this->m_capacity = capacity; this->m_size = 0; this->m_addr = new T[this->m_capacity]; } MyArray(const MyArray& arr){ if(arr.m_addr == NULL){ return; } // 深拷贝 this->m_capacity = arr.m_capacity; this->m_size = arr.m_size; this->m_addr = new T[this->m_capacity]; for(int i = 0; i < m_size; ++i){ // T 类型是可拷贝的,= 运算符也是深拷贝 this->m_addr[i] = arr.m_addr[i]; } } MyArray& operator=(const MyArray& arr){ if(this == &arr){ return *this; } if(this->m_addr !...

January 15, 2022 · 2 min · Rick Cui

类模板

一、类模板写法 1. 声明和定义写在一起 template<class T> class Person{ public: Person(T age){ this->m_age = age; } void Show(){ cout << this->m_age << endl; } private: T m_age; }; int main() { Person<int> p(20); p.Show(); cout << p << endl; printP(p); return 0; } 2. 声明和定义分开写,但在同一文件中 template<class T> class Person{ public: Person(T age); void Show(); private: T m_age; }; template<class T> Person<T>::Person(T age){ this->m_age = age; } template<class T> void Person<T>::Show(){ cout << this->m_age << endl; } int main() { Person<int> p(20); p....

January 12, 2022 · 2 min · Rick Cui

编译过程

各个 .cpp 文件是独立编译的,如果有其它的类和函数会先在本 .o 文件中生成符号,由最后的链接器去其它 .o 文件找具体的函数定义 .c .cpp 文件经过 预编译器拷贝头文件、宏展开 生成 .i 文件(文本文件) g++ -E main.cpp -o main.i .i 文件经过 编译器 生成汇编程序 .s(文本文件) g++ -S main.i -o main.s .s 文件经过 汇编器 生成可定位目标文件 .o (二进制) Windows: g++ -c main.s -o main.obj Linux: g++ -c main.s -o main.o .o 文件经过 链接器 生成可执行目标文件 .exe .dll g++ main.s -o main

January 12, 2022 · 1 min · Rick Cui