堆与拷贝构造函数

一:概述:ios

(1):c++

1:在C++中,堆分配的概念获得了扩展,不只C++的关键字new和delete能够分配和释放堆空间,并且经过new创建的对象要调用构造函数,
经过delete删除对象也要调用析构函数。

(2):c++程序的内存分配机制:数据结构

(1):c++程序的内存格局分为四个区,
1:全局数据区
2:代码区
3:堆区
4:栈区
(2):今后能够知道学习一门计算机语言,最基本的是数据结构的学习.
全局变量、静态数据、常量及字面量存放在全局数据区,全部类成员函数和非成员函数代码存放在代码区,为运行函数而分配的局部变量、函数参数、
返回数据、返回地址等存放在栈区,余下的空间都被做为堆区.

 (3):malloc(),free(),和new ,delete的区别:函数

#include <iostream>
#include "malloc.h"
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class test
{
    public:
        test(); //声名test()函数;
        ~test(); //声明test类的析构函数 
        void out_date();
    protected:
        int day = 0;
        int year = 0;
};
test::test()
{
    cout<<"执行构造函数"<<endl;
    day = 27;
    year = 2020;
 } 
test::~test()
{
    cout<<"执行析构函数"<<endl;
}
void test::out_date()
{
    cout<<"the year is "<<this->year<<endl;
    cout<<"the day  is "<<this->day<<endl;
}
int main(int argc, char** argv)
{
    test *p; //p仅仅是一个类类型的指针; 
    p = (test*)malloc(sizeof(test)); //没有调用构造函数 
    free(p); //没有调用析构函数 
    p->out_date(); //输出的结构没有通过构造函数.
    return 0;
}
【注意day出现的现象:】

/*
malloc()仅仅只是一个函数调用,他没有足够的信息来调用一个构造函数,他所接受的参数是一个unsigned long类型,返回的数据类型是一个指针.
p从malloc()那儿得到的不过是一个含有随机数据的类对象空间而已,对应的对象空间中的值不肯定。为此,须在内存分配以后再进行初始化。
*/oop

 

#include <iostream>
#include "malloc.h"
/*
1:构造函数能够有参数,因此跟在new后面的类类型也能够跟参数
2:函数结束标记“}”,要么遇到返回语句)自动调用析构函数。可是堆对象的做用域是整个程序生命期,
因此除非程序运行完毕,不然堆对象做用域不会到期.
*/
using namespace std;
class test
{
    public:
        test(); //声名test()函数;
        test(int s);//构造函数重载, 
        ~test(); //声明test类的析构函数 
        void out_date();
    protected:
        int day = 0;
        int year = 0;
};
test::test(int s)
{
    cout<<"带参数的构造函数s=="<<s<<endl; //输出3 
}
test::test()
{
    cout<<"执行构造函数"<<endl;
    day = 27;
    year = 2020;
 } 
test::~test()
{
    cout<<"执行析构函数"<<endl;
}
void test::out_date()
{
    cout<<"the year is "<<this->year<<endl;
    cout<<"the day  is "<<this->day<<endl;
}
int main(int argc, char** argv)
{
    test *p; //p仅仅是一个类类型的指针; 
//new能够根据参数来调用构造函数 
    p = new test(3); //分配堆空间,并执行构造函数 
    delete p; //手动调用析构函数 
}

(4):拷贝构造函数:即用一个对象去构造另外一个构造函数,拷贝的意思:能够理解成u盘从某硬件上拷贝来东西。学习

相关文章
相关标签/搜索