C++笔记——拷贝构造函数1

拷贝构造函数是一种特殊的构造函数,具有单个形参,此形参是对该类型的引用。

(1)一个对象以值传递的方式传入函数体 
(2)一个对象以值传递的方式从函数返回 
(3)一个对象需要通过另外一个对象进行初始化

如果一个类没有定义拷贝构造函数,编译器会默认提供拷贝构造函数。

main.cpp

#include <iostream>
#include "student.h"
#include <cstring>
#include <stdio.h>

using namespace::std;

void foo(Student stu)
{
    cout << "In fun " << __func__ << endl;
    printf("&stu = %x\n", &stu); // 调用析构函数(对应28行)
}

Student bar()
{
    Student tom("tom", 112); // 定义类对象,调用构造函数
    return tom;
}

int main()
{
    cout << "Enter main---->\n";
    Student joe("Joe", 111); // 定义类对象,调用构造函数
    Student john = joe;      // 1. 用一个对象构造另一个对象时,调用拷贝构造函数

    cout << "\nCalling foo" << endl;
    printf("&joe = %x\n", &joe);
    foo(joe);  // 2. 一个对象以值传递的方式传入函数体,也会调用拷贝构造函数
    cout << "After call of foo\n" << endl;

    Student tom = bar(); // 一个对象以值传递的方式从函数体返回,调用构造函数???
    printf("--------\n");
    // 调用析构函数(对应16行、24行、23行)
    return 0;
}



student.h

#ifndef STUDENT_H_INCLUDED
#define STUDENT_H_INCLUDED

class Student{
public:
    Student(const char *pName = "NA", int ssId = 0); // 构造函数声明并初始化
    ~Student(); // 析构函数

    Student(const Student& s); // 拷贝构造函数

    void print();

private:
    char name[40];
    int id;
};


#endif // STUDENT_H_INCLUDED


student.cpp

#include <iostream>
#include "student.h"
#include <cstring>
#include <stdio.h>

using namespace::std;

Student::Student(const char *pName, int sId) // 构造函数的定义
    :id(sId)  // 冒号表示后面要对类的数据成员进行初始化
{
    memset(name, 0, 40);
    if(pName != NULL){
        int len = strlen(pName);
        len = (len > 39) ? 39 : len;
        strncpy(name, pName, len);
    }
    cout << "constructor of student:" << name << endl;
}

Student::~Student()
{
    cout << "destructor of student:" << name << endl;
}

void Student::print()
{
    cout << "Student:" << name << endl;
}

Student::Student(const Student &s)
{
    cout << "Constructing copy !" << endl;
    printf("&s = %x\n", &s);
    strcpy(name, "copy");
    strcat(name, s.name);
    id = s.id;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值