美文网首页
C++的构造函数、拷贝构造函数、析构函数

C++的构造函数、拷贝构造函数、析构函数

作者: 爱学习的猫叔 | 来源:发表于2024-07-31 07:59 被阅读0次

核心示例代码

#define _CRT_SECURE_NO_WARNINGS

#include<stdio.h>
#include<string.h>
#include <iostream>

using namespace std;

class Student 
{
public:
    Student() {
        cout<<"构造函数" << endl;
    }

    ~Student() {
        cout << "析构函数" << endl;
    }

    Student(int width,int ptr) {
        cout << "带参构造函数" << endl;
        this->width = width;
        this->ptr = new int(ptr);
    }

    Student(const Student &stu) {
        cout << "拷贝构造函数" << endl;
        this->width = stu.width;
        this->ptr = new int(*stu.ptr);
    }

    void setWidth(int w) {
        this->width = w;
    }

    int getWidth() {
        return this->width;
    }

    void setPtr(int *ptr) {
        this->ptr = new int(*ptr);
    }

    int* getPtr() {
        return this->ptr;
    }

private:
    int width;
    int* ptr;
};

Student getStudent(int width, int ptr) {
    Student stu(width,ptr);//带参构造
    printf("getStudent %p\n",&stu);
    return stu;//拷贝构造
    //函数结束后stu会被回收走析构函数
}

void main() {
    Student *stu1 = new Student();//无参构造
    stu1->setWidth(20);
    int *p = new int(100);
    stu1->setPtr(p);
    Student *stu2 = stu1;//指针赋值,创建副本
    Student stu3 = *stu1;//指针解引用赋值,深拷贝,会调用拷贝构造函数
    cout << "%p:" << stu1 << ", %p:" << stu2 << ",%p:" << &stu3 << endl;
    
    Student stu4 = {20,100};//带参构造
    Student stu5 = stu4;//深拷贝,会调用拷贝构造函数
    cout << "%p:" << &stu4 << ",%p:" << &stu5<< endl;

    Student stu6;//无参构造
    stu6 = stu4;//默认调用=赋值操作符
    cout << "%p:" << &stu6<<endl;
    getStudent(2,3);
    getchar();
    //整个main结束,getStudent()返回的Student再次被回收,走析构函数
}

运行结果

构造函数
拷贝构造函数
%p:01223508, %p:01223508,%p:00EFFCC0
带参构造函数
拷贝构造函数
%p:00EFFCB0,%p:00EFFCA0
构造函数
%p:00EFFC90
带参构造函数
getStudent 00EFFB54
拷贝构造函数
析构函数
析构函数

相关文章

  • c++学习笔记2(GeekBand)

    拷贝构造、拷贝赋值和析构 c++中有Big Three三个特殊的函数,他们就是拷贝构造函数,拷贝赋值函数和析构函数...

  • (GeekBand)Second class

    一、Big Three:拷贝构造函数,拷贝赋值函数,析构函数 1.拷贝构造函数 文字定义:拷贝构造函数,又称复制构...

  • C++语言基础(02)

    1.可变参数 2.构造函数、析构函数、拷贝构造函数 构造函数 拷贝构造函数 //浅拷贝(值拷贝)问题 //深拷贝

  • 简介python中的析构函数与构造函数

    python的构造和析构函数为固定的名字。 构造函数 析构函数 不像c++中那样构造函数和析构函数是类名字。并且在...

  • C++面向对象高级编程(上)-第二周-博览网

    第二周 三大函数:拷贝构造,拷贝赋值,析构 字符串的构造函数,拷贝构造函数, 拷贝构造函数和拷贝赋值函数没有自主定...

  • C++boolan part1_week2

    Big Three三个特殊函数 (拷贝构造函数、拷贝赋值函数、析构函数) 1 拷贝构造函数 定义:如果一个构造函数...

  • [字符串] 自己实现一个string类(一)

    C++类一般包括:构造函数,拷贝构造函数,赋值构造函数和析构函数四大函数。 在上面的赋值构造函数中,都是先dele...

  • 三大函数

    三大函数 拷贝构造 拷贝赋值 析构函数

  • C++ 拷贝控制(二) — 移动构造函数和移动赋值运算符

    相关文章: C++ 拷贝控制(一) — 析构函数、拷贝构造函数与拷贝赋值函数 C++ 引用类型 — 左值引用、常引...

  • Boolan第二周笔记

    一、C++三个特殊的函数(Big Three):拷贝构造函数,赋值构造函数和析构函数 class里面只要有指针,就...

网友评论

      本文标题:C++的构造函数、拷贝构造函数、析构函数

      本文链接:https://www.haomeiwen.com/subject/rwfnhjtx.html