析构函数 , 构造函数, 拷贝复制函数

析构函数 , 构造函数, 拷贝复制函数

析构函数

不管类中是否定义了自己的析构函数, 编译器自动执行类中非static数据成员的析构函数

  • 当对象超出作用域或者new出来的对象要删除时

构造函数

  • 保证每个对象的数据成员具有合适的初始值

拷贝构造函数

  • 只有当个形参并且此形参是 本类对象的引用( 常为 const )
// expriment_2.cpp: 定义控制台应用程序的入口点。
//

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


// expriment_2.cpp: 定义控制台应用程序的入口点。
//

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


class CPoint
{
private:

    int x, y;
    static int nCount;   // nCount用于保存点的个数

public:

    // 构造函数
    CPoint(int px = 0, int py = 0) {
        x = px;
        y = py;
        nCount++;
    }

    // 拷贝构造
    CPoint(const CPoint& p) {
        x = p.x;
        y = p.y;
        nCount++;
    }

    // 析构
    ~CPoint() {
        cout << "deconstructor invoked" << endl;
    }

    // function of class Point
    int GetX() {
        return x;
    }
    int GetY() {
        return y;
    }
    void SetX(int px) {
        x = px;
    }
    void SetY(int py) {
        y = py;
    }
    void ShowPoint() {
        cout << "x: " << x << " y: " << y << endl;
    }
    static void showCount() {
        cout << nCount << endl;
    }
};
// static param initiante
int CPoint::nCount = 0;

int main()
{
    // 分别定义CPoint类的对象、指针、引用,对各成员函数进行调用。
    CPoint p(1, 1);
    CPoint *p1 = &p;
    CPoint & p2 = p;

    p.GetX();
    p.GetY();
    p.ShowPoint();
    p.showCount();

    p1->GetX();
    p1->GetY();
    p1->ShowPoint();
    p1->showCount();

    p2.GetX();
    p2.GetY();
    p2.ShowPoint();
    p2.showCount();

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值