您的位置:首页 > 编程语言 > C语言/C++

C++异常捕获和动态内存申请

2016-07-22 16:44 316 查看
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;
}


输出:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息