欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++拷贝构造函数 的理解

程序员文章站 2023-12-26 14:02:21
#include using namespace std; //拷贝构造函数的理解 class Point { public: Point(); Point(int X, int Y); ~Point(); Point(Point &p); void setPoint(int ......
#include <iostream>
using namespace std;
//拷贝构造函数的理解
class point
{
public:
    point();
    point(int x, int y);
    ~point();
    point(point &p);
    void setpoint(int x, int y)
    {
        x = x;
        y = y;
    }
public:
    int x, y;
};
point::point()
{
    x = 0;
    y = 0;
    cout << "缺省样式的构造函数\n";
}
point::point(int x, int y)
{
    x = x;
    y = y;
    cout << "正常构造\n";
}
point::~point()
{
    cout << "点(" << x << "," << y << ")析构函数调用完毕\n";
}
point::point(point &p)
{
    x = p.x;
    y = p.y;
    cout << "拷贝构造函数\n";
}
void f(point p)
{
    cout << "函数f之中:" << endl;
    p.setpoint(p.x, p.y);
}
void f2(point &p)
{
    cout << "函数f之中:" << endl;
    p.setpoint(p.x, p.y);
}
point g()
{
    point a(7, 33);
    cout << "函数g之中:" << endl;
    return a;
}

int main(void)
{
    point p1(10, 10);
    point p2;
    
    f(p2);
    f2(p1);
    return 0;
}
/*总结:
    1.对于f()函数的调用,首先要“调用拷贝构造函数”以实现从实参到形参的传递
相当于语句 “形参 = 实参”(p = p2),当函数类型为引用时,就不会调用拷贝构造函数。
引用相当于别名 不申请内存空间.
    2.对于构造函数和析构函数的调用时一一对应的,即“先构造的后析构”类似于栈的“先进后出”原则。
*/

 

 

上一篇:

下一篇: