C++ 构造函数_拷贝构造函数

拷贝构造函数

系统自动生成的函数:

    普通构造函数

    拷贝构造函数

如果自己定义了普通构造函数,系统不会再自动生成普通构造函数;

如果自己定义了拷贝构造函数,系统不会再自动生成拷贝构造函数。

***如果没有自定义的拷贝构造函数则系统自动生成一个默认的拷贝构造函数。

***当采用直接初始化或者复制初始化实例对象时,系统自动调用拷贝构造函数。

拷贝构造函数是一种特殊的构造函数,它在创建对象时,是使用同一类中之前创建的对象来初始化新创建的对象。拷贝构造函数通常用于:

  • 通过使用另一个同类型的对象来初始化新创建的对象。

  • 复制对象把它作为参数传递给函数。

  • 复制对象,并从函数返回这个对象。

如果在类中没有定义拷贝构造函数,编译器会自行定义一个。如果类带有指针变量,并有动态内存分配,则它必须有一个拷贝构造函数。拷贝构造函数的最常见形式如下:

classname (const classname &obj) {
   // 构造函数的主体
}

定义格式

    类名(const 类名& 变量名)

class Student
{
public:
    Student(){m_strName = "jim";} // 普通构造函数
    Student(const Student& stu){} // 拷贝构造函数

private:
    string m_strName;
}

代码示例:

demo.cpp

#include <iostream>
#include <stdlib.h>
#include <string>
#include "Teacher.h"
using namespace std;

/*************************************************************************
Teacher类
    自定义拷贝构造函数

数据成员:
    姓名
    年龄

成员函数:
    数据成员的封装函数

*************************************************************************/

void test(Teacher t){}

int main(void)
{
    Teacher t1;     // 调用普通函数
    test(t1);    // 调用拷贝构造函数
    Teacher t2 = t1;  // 调用拷贝构造函数
    Teacher t3(t1);   // 调用拷贝构造函数

    system("pause");
    return 0;
}

Teacher.h

#include<string>
using namespace std;

class Teacher
{
public:
    // 声明构造函数,参数给定默认值
    Teacher(string name = "cjj",int age = 22);

    // 声明拷贝构造函数
    Teacher(const Teacher &tea);

    // 声明成员函数,把所有的成员函数都罗列出来
    void setName(string _name);
    string getName();
    void setAge(int _age);
    int getAge();

private:
    string m_strName;
    int m_iAge;    

};

Teacher.cpp

#include"Teacher.h"
#include<iostream>
using namespace std;

// 定义构造函数,使用初始化列表,初始化构造函数的参数
//m_iMax(m)为常量,只能使用初始化列表进行初始化
Teacher::Teacher(string name,int age):m_strName(name),m_iAge(age)
{
    cout << "Teacher(string name,int age)" << endl;
}
// 定义拷贝构造函数
Teacher::Teacher(const Teacher &tea)
{
    cout<<"Teacher::Teacher(const Teacher &tea)"<<endl;
}

// 类外定义,写出成员函数的函数体
void Teacher::setName(string _name)
{
    m_strName = _name;
}
string Teacher::getName()
{
    return m_strName;
}
void Teacher::setAge(int _age)
{
    m_iAge = _age;
}
int Teacher::getAge()
{
    return m_iAge;
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/chuijingjing/p/9251418.html