c/c++语言开发共享C++拷贝构造函数 的理解

#include <iostream> 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.对于构造函数和析构函数的调用时一一对应的,即“先构造的后析构”类似于栈的“先进后出”原则。 */

 

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606193.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐