Cpp_part2
1.exception 异常处理
1 2 3 4 5 6 7 8
| void fun1(int){};
void fun(int i) { if (i == 5) { throw 1; } }
|
2.类和对象
C语言能面向对象吗?
一方面everything is object #C语言能面向对象
另一方面封装,继承,多态 #C语言不能面向对象
结构是相关属性的集合,与结构相关的操作均独立于结构之外
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| struct Student { int id; char* name; }; void init_student(Student* s, int id, char* name) { s->id = id; s->name = name; }
void Student::init_student(int aid, char* aname) { id = aid; name = aname; } void demo() { Student s; s.id = 1001; s.name = "Charles"; init_student(&s, 1001, "Charles"); }
|
故C语言解决了封装,但封装的不彻底
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Student { private: int id; string name;
public: void init_student(int id, string name) { this->id = id; this->name = name; } Student();
Student(int id, string name) { this->id = id; this->name = name; } }; Student::Student(int id, int name) { id = id; name = name; }
|
类是抽象的,对象是具体存在
类是唯一的,对象是无穷多的
类中函数不会占有对象空间
一个对象就是一段连续的内存
Main part
库程序员,终端程序员
面向对象站在库程序员的角度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cout.tie(NULL); fun1(5); try { fun(5); } catch (int e) { printf("error code is %d", e); } catch (double f) { printf("error code is %f", f); } catch (...) { printf("catch everything"); } return 0; }
|