C++异常捕获和动态内存申请
来源:互联网 发布:最新网络币 编辑:程序博客网 时间:2024/06/10 01:55
- C++提供了异常捕获类exception,我们可以用这类里面try,catch和through来捕获和抛出异常,也可以继承该类,自己定义异常。
语法为:
#include "stdio.h"#include"iostream"//异常处理类#include"exception"using namespace std;int fun(int a, int b);double division(int a, int b);int main() { int a; int b; cout << "please input a and b:" << endl; cin >> a; cin >> b; fun(a, b); try { return a / b; } catch (const std::exception&) { cout << "b is 0????" << endl; } int x = 50; int y = 0; double z = 0; try { z = division(x, y); cout << z << endl; } catch (const char* msg) { cerr << msg << endl; } return 0;}int fun(int a, int b){ if (b == 0)// throw "b cannot be zero!!!" ;//抛出异常 cout << "b cannot be zero!" << endl; return 0;}double division(int a, int b){ if (b == 0) { throw "Division by zero condition!"; } return (a / b);}
- 关于动态内存的申请
栈:日常c++申请的变量都将占用栈内存,这个都是直接由系统来分配和释放内存;
堆:有的时候不知道需要分配多大内存给变量或者数组,即在程序运行时候才知道,这时候就可以动态的分配内存。
关键词:new,delete,这两个是操作符。而c语言是通过函数来申请和释放内存的,即malloc()和free().
基本语法:
//为指针变量申请内存double *p= NULL;p=new double;*p=100.2234;//在内存空间赋值delete p;//删除内存//为数组分配内存char *p=NULL;p=new char[10];//申请10个char类型空间地址//删除空间delete [] p;//为二重数组赋值char **p=NULL;p=new char[3][4]//申请3*4空间delete []p;
为对象分配内存
#include "stdio.h"#include"iostream"using namespace std;//定义一个类class student{public: char name; char age; float whole_score(int chinese,int math, int english) { return chinese + math + english; }//定义一个构造函数 student() { cout << "构造函数!" << endl; }//定义一个析构函数 ~student() { cout << "这个是析构函数!" << endl; }private: int family;protected: int chinese = 100; int math = 20; int english = 120;};int main(){ //申请一个对象 //student s=new student[4]错误,指针可以指向数组第一个元素地址 student * S = new student[4]; delete[] S; return 0;}
输出:
0 0
- C++异常捕获和动态内存申请
- C语言动态内存申请
- C和C++中的动态申请内存函数
- 动态申请和释放内存
- 动态内存申请和释放
- C++assert和捕获异常
- C 内存申请和释放
- C和C++如何动态申请内存和释放内存?有什么区别?
- 拿来主义:C语言动态申请内存案例
- C语言 动态申请数组内存
- C和C++动态内存的申请与释放思考(动态多维数组空间分配)
- 关于动态内存的申请和释放
- 动态捕获Python异常
- 关于C/C++动态申请空间释放和内存泄漏问题介绍
- C指针(一) - 申请和释放内存
- C指针(一) - 申请和释放内存
- 动态申请内存
- 函数动态申请内存
- 链表相加
- ecshop数据库操作函数
- tabbar和navigationbar
- Ignatius and the Princess I
- Teradata Tomcat 连接池
- C++异常捕获和动态内存申请
- Windbg 自动加载到启动的进程
- nginx + lua + redis 防刷和限流
- 内存字节对齐
- 仙人球的残影
- .Net语言 APP开发平台Smobiler3.2版本将于八月中旬发布!——3.2版本预告(一)
- Android继承Mob短信验证详解
- comments 在djiano 高版本问题
- 2016年国内开源镜像站点汇总