您的位置:首页 > 其它

10.异常

2019-04-12 15:50 57 查看
  • 复习 文件流: fstream file; //
  • file.open(“文件路径”,打开方式)
  • file.close();
  • get put //字符的读写
  • getline 读取一样内容
  • cin.get()
  • read write //读写二进制文件的操作 字节直接作为单位
  • ios —>ifstream ofstream

异常处理

  • 捕获异常
#include<iostream>
#include<stdexcept>
#include <iostream>
#include<fstream>
#include<typeinfo>
try{
char *p = new char[0x7fffffff];
*p = 2;
delete[] p;
}
catch(std::bad_alloc &e)
{
std::cout<<e<<e.what()<std:endl;
}
std::cout <<typeid(s).name;
  • catch(),参数有数据类型,表示catch这类型的异常
  • catch(…)表示catch所有类型的异常
  • 异常处理一般用来在程序被迫中断前进行一些:文件保存,内存释放之类的操作
  • bad_alloc 内存申请错误
  • out_of_range 表示越界 (string at) string st = “hello”;
  • https://st.at(9); 下标为9的内容 // st[9]
  • bad_typeid 多态类指针指向NULL并且用到typeid运算符就会有错误
      typeid 运算符 用来得到类型#include
    • int s;
    • std::cout <<typeid(s).name;
  • e.what() 用来得到错误信息(字符串类型)
  • 下面的小程序用来输出传入的文件参数,并打印文件内容:

    #include "pch.h"
    #include <iostream>
    #include<fstream>
    #include<stdexcept>
    #include<typeinfo>
    using namespace std;
    
    int main(int argc,char* argv[])
    {
    for (int i = 0; i < argc; i++)
    {
    std::cout << argv[i] << std::endl;
    }
    
    if (argc >= 2)  //表示给主函数传了至少一个文件路径
    {
    fstream file;
    file.open(argv[1], ios::in);
    while (!file.eof())
    {
    cout << (char)file.get();
    }
    file.close();
    }
    cin.get();
    cin.get();
    cin.get();
    return 0;
    //F1  查看函数使用文档
    
    }

    C11的10条新标准

      1. 变量初始化 int x=2;
      2. int x(2);//c++支持的方式
      3. int x{2}; //c++支持的方式
      1. NULL

        [ol] C语言 NULL 宏定义相当于0
      2. C++ nullptr 有类型 更加安全一点
    • auto 自实行类型,根据初始化的值,确定用什么类型

      auto x =3.14
    • decltype 根据已经有的类型来定义新的变量

      auto x = 3.14;
      decltype(x) y;
    • for 用于含有迭代器的类

        string vector

        #include<string>
        string x = "nihao";
        for (auto s:x)
        {
        cout << s;
        }
        int d[] = {1,2,3,4,4,5,5,5,4};
        for (auto s:d)
        {
        cout << s;
        }
    • typedef 给类型取别名 using 给类型取别名

      typedef  int MyInt;    // C
      using myInt = int;  // C++  using 别名 = 类型名
    • 直接给对象中成员赋值

    • 用其他已经写好的构造,帮忙做一些操作 委托

      class A
      {
      int x=2; // 定义变量的时候这个X赋初值为2
      int y,z,a,b,c;
      public:
      A(int x):x(x){ x=y=z=b=c=0;}
      A(int x, int y) :A(){this->x=x;this->y=y;}
      }
    • final 多态就是子类重写父类的虚函数,,这个用来防止子类重写

    • override 放派生类中,声明中使用

      class B
      {
      public:
      B();
      ~B();
      virtual void fun(){}
      virtual void fun2() final;
      virtual void fun3() override;
      }
      class C:public B
      {
      B() = default;
      void fun()
      {
      
      }
      }
    • [/ol]
    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: