析构函数 , 构造函数, 拷贝复制函数
析构函数
不管类中是否定义了自己的析构函数, 编译器自动执行类中非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;
}