C++ 赋值号重载的拷贝构造函数代码笔记

#include <iostream>
using namespace std;

class A
{
public:
    A(int);                      //构造函数
    A(const A &);                //拷贝构造函数
    ~A();
    void print();
    int *point;
    A &operator=(const A &);     //重载使用对象引用的赋值运算符
};

A::A(int p)
{
    point = new int;
    *point = p;
    cout<<"调用构造函数"<<endl;
}

A::A(const A &b)
{
    *this = b;
    cout<<"调用拷贝构造函数"<<endl;
}

A::~A()
{
    delete point;
    cout<<"调用析构函数"<<endl;
}

void A::print()
{
    cout<<"Address:"<<point<<" value:"<<*point<<endl;
}

A &A::operator=(const A &b)
{
    if( this != &b)
    {
        delete point;
        point = new int;
        *point = *b.point;
    }
    cout<<"调用赋值号重载"<<endl;
    return *this;
}

int main()
{
    A x(2);
    A y = x;
    x.print();
    y.print();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37592750/article/details/83044053