[OOP]拷贝构造函数

拷贝构造函数是一种特殊的构造函数。copy constructor
它是构造函数,所以函数名是类名、没有返回值
它是特殊的构造函数:参数形式是固定的

class Object
{
public:
Object( const Object& other );
};

拷贝构造函数的含义: 以一个对象为蓝本,来构造另一个对象。

Object b;
Object a(b); // 或写成 Object a = b;

称作:以b为蓝本,创建一个新的对象a。

(a是b的一个拷贝/备份,两者内容完全相同)

 

拷贝构造函数从来不显式调用,而是由编译器隐式地调用。
在以下三种情况:
(1)定义对象
Object a;
Object b(a); // 或写成 Object b = a;

(2)动态创建对象
Object a;
Object* p = new Object(a);

(3)函数的传值调用
void Test(Object obj);

构造:
Object a;
Object b = a; // 或写作 Object b(a);
// 此为“构造”,在创建对象的时候给初值,拷贝构造函数被调用

赋值:
Object a(1,2);
Object b;
b = a; // 此为“赋值”,不会调用拷贝构造函数

在拷贝构造函数,可以访问参数对象的任意成员

因为它们是同类,所以访问不受限制。

Object(const Object& other)
{
this->a = other.a;
this->b = other.b;
}

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


class Object
{
public:
    Object(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    Object(const Object& other)
    {
        printf("in copy constructor...\n");
        this->a = other.a;
        this->b = other.b;
    }
private:
    int a;
    int b;
};

void Test(Object obj) // Object obj(x)
{

}

int main()
{
    Object x(1,2);

    Test(x);

// 	Object y(x); // copy
// 	Object* p = new Object(x);
// 
// 	delete p;
    return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

class Base
{
public:
    int dddd;
};
class Object : public Base
{
public:
    Object(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    Object(const Object& other):Base(other)
    {
        this->a = other.a;
        this->b = other.b;
    }
private:
    int a;
    int b;
};

int main()
{
    Object objx(1,2);
    objx.dddd = 123;

    Object objy(objx);

    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注