C++做题总结(1)

来源:互联网 发布:建站软件排行 编辑:程序博客网 时间:2024/06/10 16:01

1、malloc与free和new与delete的区别

(1)malloc和free是库函数,以字节为单位申请堆内存
(2)new和delete是关键字,以类型为单位申请堆内存
(3)malloc和free单纯的对内存进行申请与释放
(4)对于基本类型new关键字会对内存进行初始化
(5)对于类类型new和delete还负责构造函数和析构函数的调用

2、编译器对构造函数的区别

#include <cstdlib>#include <iostream>using namespace std;class Test{public:    explicit Test(int i)//只能显式调用,不能够隐式调用    {        cout<<"Test(int i)"<<endl;    }    Test(const Test& obj)    {        cout<<"Test(const Test& obj)"<<endl;    }    ~Test()    {        cout<<"~Test"<<endl;    }};void func(){    Test t1(5);    Test t2 = 5;//据我测试Test t2 = 5;等价于Test t2(5);     //默认情况下,字面量5的类型为int,因此5无法直接用于初始化Test对象;        //但是编译器在默认情况下可以自动调用构造函数;于是编译器尝试调用Test(int)生成一个临时对象;     //之后调用拷贝构造函数Test(constTest&)用临时对象对t2进行初始化。     Test t3 = Test(5);//都调用Test(int n);     Test t4;     t4 = 5;//先调用拷贝构造函数,在调用等号重载运算符}int main(int argc, char *argv[]){    func();    cout << "Press the enter key to continue ...";    cin.get();    return EXIT_SUCCESS;}

(1)C++编译器会尝试各种手段尝试让程序通过编译
(2)方式一:尽力匹配重载函数
(3)方式二:尽力使用函数的默认参数
(4)方式三:尽力尝试调用构造函数进行类型转换

0 0
原创粉丝点击